Ask a database question. The user table has a real_name field, indicating the user name. The plag table has two fields: user_id1 and user_id2. Now we want to query all the information in the plag table and output the real_name corresponding to user_id1 and user_id2 in the user table. How to Write sq... ask a database question. The user table has a real_name field, indicating the user name. The plag table has two fields: user_id1 and user_id2. Now we want to query all the information in the plag table and output the real_name corresponding to user_id1 and user_id2 in the user table. How to Write SQL statements?
For example, the user table uses two records:
Id: 1 real_name: Tom
Id: 2 real_name: Mike
The plag table has such a record.
Id: 1 user_id1: 1 user_id2: 2
I want to output plag in this form:
Id: 1 name1: Tom name2: Mike
Please give SQL and explain
Reply content:
Ask a database question. The user table has a real_name field, indicating the user name. The plag table has two fields: user_id1 and user_id2. Now we want to query all the information in the plag table and output the real_name corresponding to user_id1 and user_id2 in the user table. How to Write SQL statements?
For example, the user table uses two records:
Id: 1 real_name: Tom
Id: 2 real_name: Mike
The plag table has such a record.
Id: 1 user_id1: 1 user_id2: 2
I want to output plag in this form:
Id: 1 name1: Tom name2: Mike
Please give SQL and explain
select plag.id, group_concat(user.name order by user.id) as real_names from plag left join user on plag.user_id1 = user.id or plag.user_id2 = user.id
Although the output of this sentence is a little different, it should also meet the requirements of the subject. The output result should be:
id | realnames1 | Tom,Mike
Obtainedrealnames
Isuser.id
Result sets can be operated in order.
The following sentence can be output as expected by the landlord:
select plag.id,(select user.name from plag inner join user on user.id = plag.user_id1) as name1, (select user.name from plag inner join user on user.id = plag.user_id2) as name2 from plag
The output should be:
id | name1 | name21 | Tom | Mike
Use the inner join method.
Reference http://www.w3school.com.cn/ SQL/SQL _join_inner.asp
select p.id, u1.real_name as name1, u2.real_name as name2from plag p, user as u1, user as u2where p.user_id1 = u1.id and p.user_id2 = u2.id;