2013-01-11 70 views
1

我有以下的疑問,我想有可能合併爲一個或兩個較大的疑問:如何將這些SQL查詢合併爲更高效的MySQL?

SELECT user, password, email FROM users WHERE user = 'njp316' LIMIT 1; 

INSERT IGNORE INTO collectors_users (username, password, email, dateadded, subscribed) 
VALUES (user, password, email, NOW(), 'Y'); 

這人會拉回來多行,所以它需要循環:

SELECT barcode FROM collections WHERE user = user; 

INSERT IGNORE INTO collections_collections (username, barcode) 
VALUES (user, barcode); 

很明顯,我沒有使用SQL進行升級,所以只是尋求一些幫助。謝謝。

+0

我想你必須寫一個存儲過程。我不認爲你能以另一種方式做到這一點,但我會等待一些真正的專家加入。 – crush

+0

什麼是客戶端代碼餵養這個?即Java,C++等 – Woot4Moo

+0

客戶端代碼爲PHP –

回答

3

除非我失去了一些東西......這是非常簡單的:

INSERT IGNORE INTO collectors_users 
(username, password, email, dateadded, subscribed) 
SELECT user, password, email, NOW(), 'Y' 
FROM users 
WHERE user = 'njp316' 
LIMIT 1; 

INSERT IGNORE INTO collections_collections 
(username, barcode) 
SELECT user, barcode 
FROM collections 
WHERE user = user; 
+0

WHERE user = user; - 我希望能夠從第一個查詢中獲得用戶名。 –

0

您可以使用子查詢。

INSERT INTO collectors_users (username, password, email, dateadded, subscribed) 
SELECT user, password, email, NOW(), 'Y' FROM users WHERE user='njp316' LIMIT 1; 

它使用SELECT作爲數據源以注入INSERT。請注意,列的順序很重要。

+0

這不會僅僅插入一條記錄嗎? – crush

+0

是的,只會插入一條記錄。如果您不想限制,請放下「LIMIT」。 –

0

試試這個:

INSERT IGNORE INTO collectors_users (username, `password`, email, dateadded, subscribed) 
SELECT `user`, `password`, email, NOW(), 'Y' 
FROM users WHERE `user` = 'njp316' LIMIT 1; 

INSERT IGNORE INTO collections_collections (username, barcode) 
SELECT `user`,barcode 
FROM collections WHERE `user` = 'njp316';