To query two tables with joins

Source: Internet
Author: User
Tags join joins mail
This article is intended only as a beginner's SQL application memo
We often have to query the same and different records from a field in two tables, and it's easy to get the results you want with joins.
One, what is a join
Join: Joins represent two-table relationships, and we can think of two tables as two sets. Suppose there are two tables, we use a and B to indicate that there is one or more of the same fields in the two tables. So, there are three different sets of these:
1, Intersection: Two table records of the same field
2, a B-complement: In A, and the same field content is not equal to B records
3, B to make a supplement: in B, and the same field content does not equal a record

Second, use the connection to inquire
Join has three usages corresponding to the above three sets
1, intersection: INNER JOIN INNER JOIN
2. A B-complement: LEFT JOIN
3, B to make a supplement: Right join the right-hand join

Iii. examples
Now look at an example. There are two tables, table one: address; table two: Mail.
For simplicity, two tables have only one field, and the field name is "name." Now to get three sets:
1, a record of names in all two tables
SELECT address. Name as name
From address INNER JOIN Mail on address. Name = mail. Name;


2. A record with a name in the address and no name in the mail
SELECT address. Name
From address left JOIN Mail on address. Name = Mail. Name
WHERE ((mail. First name) is Null);


Note: This is a left join for the Address table, which is the right join for the mailing table

3, there is no name in the address and in the Mail has a name record
SELECT message. Name
From address right JOIN Mail on address. Name = Mail. Name
WHERE ((address. First name) is Null);


Note: This is a right join for the Address table, which is the left join for the mailing table

The following two can also be written in the mail table to join the Address table, which is left to write it yourself. Bluetooth and lz1220 can take a look.



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.