This article introduces mysql connection query through an interesting example, using a hybrid subquery and connection query and multiple connection queries, for more information about MySQL connection query, see MySQL connection query. connection query is often used in database query operations. The following describes MySQL connection query.
Mysql connection query:Supports multi-table join
The same table can be connected multiple times (aliases are important when connecting the same table multiple times)
Example 1:
There are two tables below
Teams table
Competition result table: result
Problem:
Get a table: main team, guest team, competition score, competition time
Method 1: Hybrid subquery and connection query
Step 1:
The code is as follows:
Select result. id, t_name as h_name, match_time, result from teams join result on teams. t_id = result. h_id
Step 2:
The code is as follows:
Select result. id, t_name as g_name from teams join result on teams. t_id = result. g_id
Get
Step 3: Connect to the above two tables based on the game IDs.
The code is 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;
You can get
The result is coming out, a little tedious.
Method 2: multiple connection queries
The code is as follows:
Select result. id, t1.t _ name as h_name, t2.t _ name as g_name, result, match_time from result
Join
Teams as t1 on result. h_id = t1.t _ id
Join
Teams as t2 on t2.t _ id = result. g_id;
You can get:
The Teams table needs to be connected twice, so an alias is required.
Example 2:
The following table is available: subject
Find such a table
Parent topic name, subtopic name
Connection query
You need aliases to connect yourself.
The code is 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;
You can get
The above is all the content of this article. I hope you will like it.