2011-10-14 48 views
0

這可以很容易地編寫腳本,但我想了解如何在純SQL中執行此操作。我有一個users表。在users表中,id是主鍵。現在想象我有一張名爲foos的新表。每個用戶可以有一個foo。我希望能夠爲users表中的每個用戶創建一行(不重要,如果數據現在是相同的),則表foosfoos只有兩列,user_id,nameMySQL:查詢爲父行中的每個主鍵創建一行

什麼是循環訪問用戶並在foos中爲每個用戶創建相應行的最佳方式,其中user_id是user.id,name是任何隨機字符串。

+0

所以,你只是想複製'user.id'?或者'user.name'呢?因爲創建隨機字符串不是微不足道的。 –

回答

4
insert into foo (user_id, name) 
select id, SomeStringInUserThatDoesntMatter 
from users 

OR

insert into foo (user_id, name) 
select id, 'This fixed string' 
from users 

OR(有一個有趣的一點)

insert into foo (user_id, name) 
select id, '4' 
from users 

以來,

RFC 1149.5 specifies 4 as the standard IEEE-vetted random number.

+1

對於XKCD參考+1。 – 0xCAFEBABE

2

我要說它會像這個:

insert into if not exists foo (user_id, name) 
select user_id, "any random stuff" from users; 

您需要注意,運行它兩次不會遇到錯誤,所以我們需要「if not exist」子句。

+0

考慮到可重用性(不,我不確定這是否是一個真正的詞)。 –

相關問題