![](/img/trans.png)
[英]Insert data from a table to another one in MySQL with where condition
[英]Mysql INSERT INTO from another table with condition and limit
我有兩個表有一對多關系table1(一),table2(很多)。
table1 has (t1_id) as KEY
table2 has (t2_id) as KEY and t2_t1_id as as refference to table1
現在在table1
我需要一個列( rand_t2_id
)來保存來自table2
的id
,我真的不在乎哪一個
這是我試過的查詢
INSERT INTO table1 (rand_t2_id)
SELECT t2_id
FROM table2
WHERE table1.t1_id = table2.t2_t1_id;
如果需要,還需要在某個地方建立限制。 我只需要table2中的一個id
這里沒有運氣,有人知道修復嗎?
IMO你可以試試
UPDATE table1 t1 INNER JOIN table2 t2
ON t1.t1_id = t2.t2_t1_id;
SET t1.rand_t2_id = t2.t2_id
我假設你的table1
上已經有一個名為rand_t2_id
的列。
INSERT INTO table1 (t2_t1_id, rand_t2_id)
SELECT t2_id
FROM ( SELECT t2_id, t2_t1_id
FROM table2
ORDER BY RAND()) AS h
GROUP BY t2_t1_id
ON DUPLICATE KEY UPDATE rand_t2_id = VALUES(rand_t2_id)
我想那就是你要追求的?
此查詢會將隨機t2_id插入到相關的table1中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.