Question

I have following two tables:

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

I want to select two uid's from chat_users by name and insert them as a pair into chat_friends as shown in my example. I don't know, how I can make this work. Is this kind of query possible without php and/or temporary tables?

Was it helpful?

Solution

you can specify 2 names and JOIN chat_users with itself and see if the 2 names matches and insert like below

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

alternately you can just individually select the uid of each name as below too if you prefer.

insert into chat_friends(user,friend)
select (select uid from chat_users where name = 'foo'),
       (select uid from chat_users where name = 'bar');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top