[英]Mysql INSERT INTO from another table with condition and limit
I have two tables that have a one-to-many relationship table1 (one), table2 (many). 我有两个表有一对多关系table1(一),table2(很多)。
table1 has (t1_id) as KEY
table2 has (t2_id) as KEY and t2_t1_id as as refference to table1
Now in table1
I need a column ( rand_t2_id
) that holds an id
from table2
, I do not really care which one 现在在table1
我需要一个列( rand_t2_id
)来保存来自table2
的id
,我真的不在乎哪一个
This is the query I tried 这是我试过的查询
INSERT INTO table1 (rand_t2_id)
SELECT t2_id
FROM table2
WHERE table1.t1_id = table2.t2_t1_id;
There also needs to be a limit build in somewhere if that is needed. 如果需要,还需要在某个地方建立限制。 I only need one id from table2 我只需要table2中的一个id
No luck here tho, anyone know a fix? 这里没有运气,有人知道修复吗?
IMO you could try IMO你可以试试
UPDATE table1 t1 INNER JOIN table2 t2
ON t1.t1_id = t2.t2_t1_id;
SET t1.rand_t2_id = t2.t2_id
I assume you already have a column named rand_t2_id
on your table1
. 我假设你的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)
I suppose that's what you're after? 我想那就是你要追求的?
This query would insert a random t2_id into relevant table1. 此查询会将随机t2_id插入到相关的table1中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.