Section 8 Self-join in SELECT statements

Source: Internet
Author: User

Section 8 Self-join in select statements

So far, we have connected two different tables. can we establish a self-connection for a table? The answer is yes.
Is it necessary to connect a table? The answer is yes.

Table alias:
A table can be connected by itself. We need a mechanism to differentiate two instances of a table during the self-Join Operation.
In the from clause, we can get different aliases for this table, and then use the alias in other places of the statement.
Use dot to connect the alias and field name.

Here we also provide two tables to explain the self-join.
Edinburgh bus line,

Station table:
Stops (ID, name)

Bus Route table:
Route (Num, company, POs, stop)

For more detailed explanations of the two tables, refer to here: http://sqlzoo.cn/buses.htm

1. Perform a self-connection to the route table of the bus route.

Select * From Route R1, route r2
Where r1.num = r2.num and r1.company = r2.company

In the route table, fields (Num, company) are used for self-join. What does the result mean?
You can know any two interconnected stations on each bus line.

2. Use the stop field to establish a self-connection to the route (bus route table.

Select * From Route R1, route r2
Where r1.stop = r2.stop;

The query result is all bus lines that share the same station. Does this result make sense for the transfer.

From the two examples, we can see that the self-join syntax structure is very simple, but the semantic result is often not
So easy to understand. The two tables listed here can solve many practical problems if they are used properly,
For example, how to transfer between any two sites.

SELECT R1.company, R1.num
FROM route R1, route R2, stops S1, stops S2
WHERE R1.num = R2.num AND R1.company = R2.company
AND R1.stop = S1.id AND R2.stop = S2.id
AND S1.name = 'craiglockhart'
AND S2.name = 'tollcross'

For more self-join exercises, go to the http://sqlzoo.cn/6.htm to practice.

 

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.