当前位置:网站首页>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 .
边栏推荐
- The spiral matrix of the force buckle rotates together (you can understand it)
- 解决 uni-starter 使用本地函数可以登录微信 但是使用云函数登录失败
- Su Chunyuan, founder of science and technology · CEO of Guanyuan data: making business use is the key to the Bi industry to push down the wall of penetration
- VSCode如何调试Nodejs
- Typo in static class property declarationeslint
- 自动化渗透扫描工具
- Complete set of JS array common operations
- Grpc middleware implements grpc call retry
- The vs compiled application is missing DLL
- How vscode debug nodejs
猜你喜欢

Problem handling of repeated restart during Siemens botu installation

"After 00" is coming! Digital data ushers in a new generation of "codeless" forces
![[NLP] next stop, embossed AI](/img/fc/4997309d0d53c5b6eb441ac39e6929.jpg)
[NLP] next stop, embossed AI

Regular expression and bypass cases
![[oauth2] III. interpretation of oauth2 configuration](/img/31/90c79dbc91ee15c353ec46544c8efa.png)
[oauth2] III. interpretation of oauth2 configuration

Su Chunyuan, founder of science and technology · CEO of Guanyuan data: making business use is the key to the Bi industry to push down the wall of penetration

Attributeerror: module 'distutils' has no attribute' version error resolution

Deep learning 1 perceptron and implementation of simple back propagation network

Strongly connected component
![[C language note sharing] - dynamic memory management malloc, free, calloc, realloc, flexible array](/img/3f/35c9ff3be5c0ef781ffcb537287a20.png)
[C language note sharing] - dynamic memory management malloc, free, calloc, realloc, flexible array
随机推荐
Time series of machine learning
JS judge whether it is an integer
C language large and small end mode judgment function
The fourth edition of probability and mathematical statistics of Zhejiang University proves that the absolute value of the correlation coefficient of random variables X and Y is less than 1, and some
The fourth edition of Zhejiang University probability proves that the uncorrelation of normal distribution random variables is equivalent to independence
IntelliSense of Visual Studio: 'no members available'
JS judge whether the data is empty
AtCoder Beginner Contest 261 F // 树状数组
spark:指定日期输出相应日期的日志(入门级-简单实现)
2022年IAA行业品类发展洞察系列报告·第二期
解决 uni-starter 使用本地函数可以登录微信 但是使用云函数登录失败
Where can Huatai Securities open an account? Is it safe to use a mobile phone
REST风格
Bibliometrix: dig out the one worth reading from thousands of papers!
Beijing all in one card listed and sold 68.45% of its equity at 352.888529 million yuan, with a premium rate of 84%
After reading this article, I found that my test cases were written in garbage
电赛设计报告模板及
“00后”来了!数睿数据迎来新生代「无代码」生力军
Learn science minimize
交换