Classic Mysql Connection Query example _mysql

Source: Internet
Author: User

MySQL Connection query I believe we all have some understanding, the connection query is in the database query operation often used, the following is to introduce you to the MySQL connection query

MySQL connection query: support multiple Table connection

You can repeat the connection multiple times on the same table (aliases are important when connecting to the same table more than one time)

Example 1:

Here are 2 sheets.

Teams table

Game Results Table: Result

Problem:

Draw a table: The home team, the visitors, the results, the game time

Method One: Subquery and join query mix

Step1:

Copy Code code as follows:
Select Result.id, t_name as H_name,match_time,result from teams join result on teams.t_id=result.h_id

Step2:

Copy Code code as follows:
Select Result.id, t_name as g_name from teams join result on teams.t_id=result.g_id

Get

step3: Connect the above two tables according to the match ID equal

Copy Code code as follows:
Select T1.id,h_name,g_name,result,match_time from
(select Result.id, t_name as H_name,match_time,result from teams join result on teams.t_id=result.h_id) as T1
Join
(select Result.id, t_name as g_name from teams join result on teams.t_id=result.g_id) as T2
On T1.id=t2.id;

Can be

The result is out, a little cumbersome

Method Two: Multiple connection query

Copy Code code as follows:
Select Result.id,t1.t_name as H_name, t2.t_name as G_name, result,match_time from
Join
Teams as T1 on result.h_id=t1.t_id
Join
Teams as T2 on T2.T_ID=RESULT.G_ID;

can be obtained:

Teams table to be connected 2 times so you have to have an alias.

Example 2:

The existing table subject

Ask for such a table

Name of parent column, sub column

Connection Query

You need more aliases to connect yourself.

Copy Code code as follows:
Select T1.name as p_name,t2.name as son_name from subject as T1 join subject as T2 on T1.id=t2.pid;

Can be

The above is the entire content of this article, I hope you can enjoy.

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.