简体   繁体   中英

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 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

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

No luck here tho, anyone know a fix?

IMO you could try

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM