Sql Join用于根据两个或多个表格中的列之间的关系,来查询数据
一道面试题:
两个SQL表描述如下:
部门表(department)
+——+———-+
| id | name |
+——+———-+
| 1 | caiwu |
| 2 | xiaoshou |
| 3 | kefu |
+——+———-+
员工表(employee)
+——+——-+—————+
| id | name | id_department |
+——+——-+—————+
| 1 | zhang | 1 |
| 2 | li | 1 |
| 3 | wang | 3 |
| 4 | zhao | 3 |
+——+——-+—————+
用一个sql语句输出以下统计表
+——+———-+—–+
| id | name | num |
+——+———-+—–+
| 1 | caiwu | 2 |
| 2 | xiaoshou | 0 |
| 3 | kefu | 2 |
+——+———-+—–+
sql语句:
SQL Server/MS Access
select d.*,e.isnull(num,0) num from department d
left join
(
select id_department,count(*) num from employee group by id_department
)e on e.id_department = d.id;
MySQL(实测)
select d.*,ifnull(e.num,0) num from department d
left join
(
select id_department,count(*) num from employee group by id_department
)e
on e.id_department = d.id;
SQL Inner Join(与Join相同):在表中存在至少一个匹配时,Inner Join关键字返回行,语法:
SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SQL Left Join:返回左表(table_name1)中所有的行,即使右表中没有匹配行,语法:
SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SQL Right Join:返回右表中所有的行,即使左表中没有匹配行,语法:
SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
SQL Full Join:只要某个表中存在匹配行,即返回,语法:
SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
该问题中还涉及到表别名(Oracle 不支持AS关键字。要在 Oracle 中使用别名,可以不用AS,简单地指定列名即可(因此,应该是Customers C,而不是Customers AS C)。),count()函数等。