Ask a database question. The user table has a Real_name field that represents the username. Plag table has two fields User_id1, User_id2, now to query Plag table all the information, while USER_ID1, user_id2 corresponding to the user table Real_name also output. How to write SQL?
For example: User table with 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 would like to be able to export the Plag in this form:
Id:1 Name1:tom Name2:mike
Ask the great God to give SQL and explain
Reply content:
Ask a database question. The user table has a Real_name field that represents the username. Plag table has two fields User_id1, User_id2, now to query Plag table all the information, while USER_ID1, user_id2 corresponding to the user table Real_name also output. How to write SQL?
For example: User table with 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 would like to be able to export the Plag in this form:
Id:1 Name1:tom Name2:mike
Ask the great God to give SQL and explain
Although the output is a bit out of the way, but should also meet the requirements of the main, the output should be:
The resulting realnames
set is ordered user.id
and the result sets are actionable.
The following sentence can get the output of the landlord hope:
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
You should 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;