我们做了三个范式,做了一些拆表的操作,可是有时我们确实同时显示两个表中的内容,那么就需要进行表连接操作。
显示每个学生学过的课程:
select name,course from employee,training where empoyee.eid=training.eid;
求各部门的人数和各部门姓李的人数:
各部门的人数:(select department,count(*) from employee group by department)e;
各部门姓李的人数:(select department,count(*) from employee where name like '李%' group by department)ee;
select e.department,c '各部门的名字',cc '各部门姓李的名字'
from(select department ,count(*) from employee group by department) e,
(select department ,count(*) cc from employee where name like '李%' group by department)ee
where e.department=ee.department;
在SQL中表连接是用join,有逗号的地方用join代替,而消除笛卡儿集的语句用on.
使用join 看起来更加规范,还有一个好处就是join 的话句富有变化,我们可以使用left join(左连接) 或right join(右连接),如果是左连接,不依照左边表,将右边表加入进付出。左连接可以确保左边表的每一项一定会被显示出来。
select e.department,c '各部门的名字',cc '各部门姓李的名字' from(select department ,count(*) from employee group by department) e left join(select department ,count(*) cc from employee where name like '李%' group by department)ee on e.department=ee.department;
显示null很讨厌,这个地方应该显示0,MySQL提供了一个替换null的函数ifnull,如果内容不是空,就显示内容本身,如果内容是空,就显示预设的一个值。
select e.department,ifnull(c,0) '各部门的名字',ifnull(cc,0) '各部门姓李的名字' from(select department ,count(*) from employee group by department) e left join(select department ,count(*) cc from employee where name like '李%' group by department)ee on e.department=ee.department;
网友评论