插入选择

时间:2014-01-25 23:05:19

标签: mysql insert multiple-select

我有以下两个表:

chat_users:      chat_friends:
+-----+------+   +------+--------+
| uid | name |   | user | friend |
+-----+------+   +------+--------+
|   1 | foo  |   |    1 |      2 |
|   2 | bar  |   +------+--------+
+-----+------+

我想从uid chat_users选择两个name,然后将它们作为一对插入到chat_friends中,如我的示例所示。我不知道,我怎么能做到这一点。没有php和/或临时表,这种查询是否可行?

1 个答案:

答案 0 :(得分:1)

你可以自己指定2个名字和JOIN chat_users,看看这2个名字是否匹配,如下所示插入

insert into chat_friends(user,friend)
select cu1.uid,cu2.uid
from chat_users cu1 JOIN chat_users cu2
where cu1.name = 'foo'
  and cu2.name = 'bar';

sqlFiddle

如果您愿意,也可以单独选择每个名称的uid。

insert into chat_friends(user,friend)
select (select uid from chat_users where name = 'foo'),
       (select uid from chat_users where name = 'bar');