当前位置:网站首页>Self join usage of SQL
Self join usage of SQL
2022-07-24 14:41:00 【Night drift ice】
How to use JOIN Clause , For many different tables , Use public columns , To combine information .
And for the same table , Can also be used JOIN function .
Let's introduce , What is? SELF JOIN, How it works , When do you need it .
In this article, we will discuss what a self join is, how it works, and when you need it in your SQL queries.
When using the table name, use an alias (Aliases), Used to distinguish different contents of the same table .
The grammar is as follows :
SELECT column_name(s)
FROM table1 T1
JOIN table1 T2
ON condition;
Or not JOIN Clauses can achieve the same effect :
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
Examples are as follows :
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City
FROM Customers A
JOIN Customers B
ON A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
or
SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
above SQL sentence , Will be different in the same city ID All the customers found out .
However, the significance of this example is not very clear , It just introduces the syntax used .
The following example is clearer , The data in the following table :
Employees surface
Id | FullName | Salary | ManagerId |
1 | John Smith | 10000 | 3 |
2 | Jane Anderson | 12000 | 3 |
3 | Tom Lanon | 15000 | 4 |
4 | Anne Connor | 20000 | |
5 | Jeremy York | 9000 | 1 |
This table shows employee data , Every employee has one ID, And the supervisor's ID. This is a very common organizational structure information .
We now want to display the name information of each employee's supervisor ,SQL The statement is as follows :
SELECT
employee.Id,
employee.FullName,
employee.ManagerId,
manager.FullName as ManagerName
FROM Employees employee
JOIN Employees manager
ON employee.ManagerId = manager.Id
The result is :
Id | FullName | ManagerId | ManagerName |
1 | John Smith | 3 | Tom Lanon |
2 | Jane Anderson | 3 | Tom Lanon |
3 | Tom Lanon | 4 | Anne Connor |
5 | Jeremy York | 1 | John Smith |
This SQL Inquire about (query) sentence , Display the information of employees with supervisors , And take the supervisor's ID And the name .
And the information in this employee table , Although the information format of each record is the same , But it is classified , There are two roles: employee and supervisor .
So when we execute SELF JOIN when , It's actually the same table , But formally, they are regarded as employees and supervisors .
In terms of expression , We use the alias of the table , Used to distinguish the different roles of the table .
Pay attention to the above employees ID by 4 when , There is no supervisor , If you want to display all employees , Then use LEFT JOIN.
SELECT
employee.Id,
employee.FullName,
employee.ManagerId,
manager.FullName as ManagerName
FROM Employees employee
LEFT JOIN Employees manager
ON employee.ManagerId = manager.Id
give the result as follows :
Id | FullName | ManagerId | ManagerName |
1 | John Smith | 3 | Tom Lanon |
2 | Jane Anderson | 3 | Tom Lanon |
3 | Tom Lanon | 4 | Anne Connor |
4 | Anne Connor | ||
5 | Jeremy York | 1 | John Smith |
And the default. JOIN yes INNER JOIN, Use ordinary FROM ... WHERE Clauses can also be substituted .
But if it is LEFT、RIGHT、FULL JOIN, It's useless FROM...WHERE Clause to do .
SLEF JOIN The function of :
1, Process hierarchical data (Hierarchy)
Data in the same table , A row of data has a hierarchical relationship with other row data . You can be a father son relationship .
adopt LEFT JOIN, To show this relationship .
In addition to the above employees and supervisors , It can also be Human The parent-child relationship in the table :
Human surface
Id | Name | Age | ParentId |
1 | Jonathan | 5 | 3 |
2 | Alexandra | 7 | 3 |
3 | Barbara | 30 |
function SQL:
SELECT
child.Id as ChildId,
child.FirstName as ChildFirstName,
child.Age as ChildAge,
child.ParentId,
parent.FirstName as ParentFirstName,
parent.age as ParentAge
FROM Human child
INNER JOIN Human parent
ON child.ParentId = parent.Id
have access to SELF JOIN To the result set of parent-child relationship :
ChildId | ChildFirstName | ChildAge | ParentId | ParentFirstName | ParentAge |
1 | Jonathan | 5 | 3 | Barbara | 30 |
2 | Alexandra | 7 | 3 | Barbara | 30 |
There is also the inclusion relationship of categories , Such as the following food classification :
Category surface
Id | Quantity | Category | ParentCategoryId |
1 | 60 | Food | |
2 | 50 | Fruit | 1 |
3 | 40 | Apple | 2 |
4 | 20 | Granny Smith | 3 |
5 | 100 | Milk | 1 |
6 | 60 | Soy Milk | 5 |
7 | 40 | Cow Milk | 5 |
8 | 30 | Whole Milk | 7 |
9 | 10 | Fat-Free Milk | 7 |
function SQL:
SELECT
category.Id,
category.Quantity,
category.Category,
category.ParentCategoryId,
parentcategory.Category as ParentCategory
FROM Category category
JOIN Category parentcategory
ON category.ParentCategoryId = parentcategory.Id
Get the results :
Id | Quantity | Category | ParentCategoryId | ParentCategory |
2 | 50 | Fruit | 1 | Food |
3 | 40 | Apple | 2 | Fruit |
4 | 20 | Granny Smith | 3 | Apple |
5 | 100 | Milk | 1 | Food |
6 | 60 | Soy Milk | 5 | Milk |
7 | 40 | Cow Milk | 5 | Milk |
8 | 30 | Whole Milk | 7 | Cow Milk |
9 | 10 | Fat-Free Milk | 7 | Cow Milk |
So this SELF JOIN The first function of , Is a column as ID, It's a unique identity , Another column identifies the belonging relationship ID, Can be repeated .
The data structure is actually a level diagram of level by level classification .
In execution SELF JOIN when , The correspondence is one-to-one , The number of result sets is less than or equal to the first column ID Count .
2, Show the pairing relationship in the table
Like the following colleagues surface :
Id | FullName | Age |
1 | Bart Thompson | 43 |
2 | Catherine Anderson | 44 |
3 | John Burkin | 35 |
4 | Nicole McGregor | 29 |
Suppose we want to generate a table , List all the possibilities of a pair of colleagues , In this way, everyone has the opportunity to talk to each other :
SELECT
teammate1.FullName as Teammate1FullName,
teammate1.Age as Teammate1Age,
teammate2.FullName as Teammate2FullName,
teammate2.Age as Teammate2Age
FROM Colleagues teammate1
CROSS JOIN Colleagues teammate2
ON teammate1.FullName <> teammate2.FullName
The result is :
Teammate1FullName | Teammate1Age | Teammate2FullName | Teammate2Age |
Catherine Anderson | 44 | Bart Thompson | 43 |
John Burkin | 35 | Bart Thompson | 43 |
Nicole McGregor | 29 | Bart Thompson | 43 |
Bart Thompson | 43 | Catherine Anderson | 44 |
John Burkin | 35 | Catherine Anderson | 44 |
Nicole McGregor | 29 | Catherine Anderson | 44 |
Bart Thompson | 43 | John Burkin | 35 |
Catherine Anderson | 44 | John Burkin | 35 |
Nicole McGregor | 29 | John Burkin | 35 |
Bart Thompson | 43 | Nicole McGregor | 29 |
Catherine Anderson | 44 | Nicole McGregor | 29 |
John Burkin | 35 | Nicole McGregor | 29 |
The results here , Remove the pairing between yourself and yourself . This relationship is different from the previous one to many , It becomes many to many . This becomes the product relation .
Notice the keywords used here :CROSS JOIN, Effect and JOIN It's the same , It just means Cartesian product .
such as :
SELECT * FROM table1 CROSS JOIN table2;
The result is to table1 and table2 Multiply the records of , Match separately .
3, When combining multiple tables , Multiple operations on the same table JOIN
When combining data between tables , Sometimes multiple information to be added belong to the same table , This is about to JOIN The same table more than once .
The following table :
Airport Airport Information
AirportId | Country | City |
1 | USA | New York |
2 | Canada | Toronto |
3 | Germany | Frankfurt |
4 | France | Paris |
5 | Italy | Rome |
Flight flight
FlightId | AirplaneId | StartTimestamp | EndTimestamp | StartAirportId | EndAirportId |
2 | 555877 | 2020-01-14 13:00:00 | 2020-01-14 15:00:00 | 3 | 4 |
3 | 222536 | 2020-02-04 01:00:00 | 2020-02-04 16:00:00 | 1 | 5 |
4 | 111745 | 2020-02-15 09:00:00 | 2020-02-15 12:00:00 | 5 | 4 |
5 | 777524 | 2020-02-24 03:00:00 | 2020-02-24 19:00:00 | 4 | 2 |
6 | 888521 | 2020-03-25 10:00:00 | 2020-03-25 12:00:00 | 2 | 1 |
7 | 444937 | 2020-04-01 00:00:00 | 2020-04-01 17:00:00 | 3 | 1 |
243 | 111654 | 2020-01-01 02:00:00 | 2020-01-01 04:00:00 | 1 | 2 |
To display the start and end information of the flight , Will be JOIN The airport watch twice :
SELECT
flight.FlightId,
flight.AirplaneId,
flight.StartAirportId,
startairport.Country as StartAirportCountry,
startairport.City as StartAirportCity,
flight.EndAirportId,
endairport.Country as EndAirportCountry,
endairport.City as EndAirportCity
FROM Flight flight
JOIN Airport startairport
ON flight.StartAirportId = startairport.AirportId
JOIN Airport endairport
ON flight.EndAirportId = endairport.AirportId
Get the results :
FlightId | AirplaneId | StartAirportId | StartAirportCountry | StartAirportCity | EndAirportId | EndAirportCountry | EndAirportCity |
1 | 111654 | 1 | USA | New York | 2 | Canada | Toronto |
2 | 555877 | 3 | Germany | Frankfurt | 4 | France | Paris |
3 | 222536 | 1 | USA | New York | 5 | Italy | Rome |
4 | 111745 | 5 | Italy | Rome | 4 | France | Paris |
5 | 777524 | 4 | France | Paris | 2 | Canada | Toronto |
6 | 888521 | 2 | Canada | Toronto | 1 | USA | New York |
7 | 444937 | 3 | Germany | Frankfurt | 1 | USA | New York |
Reference resources :
What Is a Self Join in SQL? An Explanation With Seven Examples | LearnSQL.com
LearnSQL.com Provide one-stop-shop, One stop SQL Learning services .
边栏推荐
- Clear all spaces in the string
- Spark: get the access volume of each time period in the log (entry level - simple implementation)
- JS judge whether it is an integer
- Problem handling of repeated restart during Siemens botu installation
- Nodejs uses the express framework to post the request message "badrequesterror:request aborted"
- Beijing all in one card listed and sold 68.45% of its equity at 352.888529 million yuan, with a premium rate of 84%
- Conversion of timestamp and time in Excel
- The solution to the error of [installation detects that the primary IP address of the system is the address assigned by DHCP] when installing Oracle10g under win7
- 解决 uni-starter 使用本地函数可以登录微信 但是使用云函数登录失败
- JS judge whether the data is empty
猜你喜欢

Data analysis and mining 1

Leetcode high frequency question 56. merge intervals, merge overlapping intervals into one interval, including all intervals
![[matlab] matlab drawing Series II 1. Cell and array conversion 2. Attribute cell 3. delete Nan value 4. Merge multiple figs into the same Fig 5. Merge multiple figs into the same axes](/img/4d/b0ba599a732d1390c5eeb1aea6e83c.png)
[matlab] matlab drawing Series II 1. Cell and array conversion 2. Attribute cell 3. delete Nan value 4. Merge multiple figs into the same Fig 5. Merge multiple figs into the same axes

Bibliometrix: dig out the one worth reading from thousands of papers!

Regular expression and bypass cases

mysql

Don't lose heart. The famous research on the explosive influence of Yolo and PageRank has been rejected by the CS summit

Detailed explanation of address bus, data bus and control bus

不要灰心,大名鼎鼎的YOLO、PageRank影响力爆棚的研究,曾被CS顶会拒稿

Decrypt "sea Lotus" organization (domain control detection and defense)
随机推荐
基于ABP实现DDD--实体创建和更新
深度学习中的学习率调整策略(1)
Learning and thinking about the relevant knowledge in the direction of building network security knowledge base
threw exception [Circular view path [index]: would dispatch back to the current handler URL [/index]
C language -- program environment and preprocessing
A common Dao class and util
LeetCode·每日一题·1184.公交站间的距离·模拟
The sliding window of Li Kou "step by step" (209. The smallest sub array, 904. Fruit baskets)
[oauth2] III. interpretation of oauth2 configuration
Bibliometrix: dig out the one worth reading from thousands of papers!
Error when using Fiddler hook: 502 Fiddler - connection failed
Unity 委托 (Delegate) 的简单理解以及实现
Number of bytes occupied by variables of type char short int in memory
“00后”来了!数睿数据迎来新生代「无代码」生力军
Solve the problem that uni starter can log in to wechat with local functions, but fails to log in with cloud functions
PIP source switching
Conversion of timestamp and time in Excel
Data analysis and mining 1
Simple understanding and implementation of unity delegate
Class loading mechanism and parental delegation mechanism