SQL Join

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()函数等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值