Problems with a MySQL multi-table query

Source: Internet
Author: User
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;
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.