1

我有两个具有一对多关系的表 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包含idfrom的列 ( ) table2,我真的不在乎哪一个

这是我试过的查询

INSERT INTO table1 (rand_t2_id)
SELECT t2_id
FROM table2
WHERE table1.t1_id = table2.t2_t1_id;

如果需要,还需要在某处建立限制。我只需要 table2 中的一个 id

运气不好,有人知道解决方法吗?

4

2 回答 2

5

海事组织你可以试试

UPDATE table1 t1 INNER JOIN table2 t2
  ON t1.t1_id = t2.t2_t1_id;
SET t1.rand_t2_id = t2.t2_id

我假设您rand_t2_idtable1.

于 2012-04-24T07:39:39.213 回答
0
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。

于 2012-04-24T07:39:30.803 回答