DataBase -- JOIN

SQL JOIN:用于根据两个或多个表中列的关系,从这些表中查数据。

(为了得到完整数据,我们需要从两个或多个表中获取结果。)

例如W3School中列出的实例,使用如下语句:

select Persons.LastName, Persons.FirstName, Orders.OrderNo
from Persons
inner Join orders
on Persons.Id_p = Orders.Id_p
order by Persons.LaseName
  • 除了上面的inner join还有以下几种连接:
    • JOIN:如果表中至少有一个匹配,则返回行;
    • LEFT JOIN:即使右表中没有匹配,也从左表返回所有的行;
    • RIGHT JOIN:即使左表中没有匹配,也从右表中返回所有的行;
    • FULL JOIN:只要其中一个表中存在匹配,则返回行。

 

  • INNER JOIN语法:(INNER JOIN 与 JOIN是相同的)
SELECT column_names 
FROM table_name1
INNER JION table_name2
ON table_name1.column_name = table_name2.column_name

 

  •  LEFT JOIN语法:
SELECT column_names
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name = table_name2.column_name
  • RIGHT JOIN语法:
SELECT column_names
FROM table_name1
RIGHT JOIN tale_name2
ON table_name1.column_name = table_name2.column_name
  • FULL JOIN语法:
SELECT column_names
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name = table_name2.column_name

 

 

Question:

Table: Person

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
+-------------+---------+
PersonId is the primary key column for this table.

Table: Address

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| AddressId   | int     |
| PersonId    | int     |
| City        | varchar |
| State       | varchar |
+-------------+---------+
AddressId is the primary key column for this table.

 

Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:

FirstName, LastName, City, State

 

Analysis:

写一个SQL语句, 返回Person表格中的以下信息,不管这些people是否有住址信息。

使用上面的LEFT JOIN语句。

 

Answer:

select Person.FirstName, Person.LastName, Address.City, Address.State
from Person
left join Address
on Person.PersonId = Address.PersonId;

 

 

  

posted @ 2016-03-05 20:08  江湖小妞  阅读(395)  评论(0编辑  收藏  举报