連表查詢
上面兩張表經過笛卡爾積獲得一個全量拼接的大表;html
笛卡爾積:python
1
|
select
*
from
employee,department;
|
內鏈接(inner join)
雙方可以互相匹配的項纔會被顯示出來;ide
select * from 表1 inner join 表2 on 條件 例如: select * from employee inner join department on employee.dep_id = department.id;
表的重命名:post
1
2
|
select t1.name,t2.name
from
employee as t1 inner join department as t2
on t1.dep_id
=
t2.
id
;
|
外鏈接
左外鏈接
左外鏈接(left join) 只完整的顯示左表中的全部內容,以及右表中與左表匹配的項;url
1
2
3
4
5
|
select
*
from
表
1
left join 表
2
on 條件
例如:
select
*
from
employee left join department
on employee.dep_id
=
department.
id
;
|
右外鏈接
右外鏈接(right join) 只完整的顯示右表中的全部內容,以及左表中與右表匹配的項;spa
1
2
3
4
5
|
select
*
from
表
1
right join 表
2
on 條件
例如:
select
*
from
employee right join department
on employee.dep_id
=
department.
id
|
全外鏈接
全外鏈接 永遠顯示左表和右表中全部的項,關鍵字(union)code
1
2
3
4
5
6
7
|
例如:
select
*
from
employee left join department
on employee.dep_id
=
department.
id
union
select
*
from
employee right join department
on employee.dep_id
=
department.
id
|
子查詢
#1:子查詢是將一個查詢語句嵌套在另外一個查詢語句中。 #2:內層查詢語句的查詢結果,能夠爲外層查詢語句提供查詢條件。 #3:子查詢中能夠包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等關鍵字 #4:還能夠包含比較運算符:= 、 !=、> 、<等
# 查"技術"部的全部員工的名字 # select name from employee where dep_id = (select id from department where name = '技術'); # 查"技術"和"銷售"部的全部員工的名字 # select name from employee where dep_id in (select id from department where name in ('技術','銷售'));
練習:
1.找出年齡大於25歲的員工以及員工所在的部門 select e.name,d.name from employee e inner join department d on e.dep_id = d.id where e.age>25 2.之內鏈接的方式查詢employee和department表,而且以age字段的升序方式顯示 select * from employee e inner join department d on e.dep_id = d.id order by e.age

1. 查詢平均年齡在25歲以上的部門名 select dep_id from employee group by dep_id having avg(age)>25 select name from department where id in (select dep_id from employee group by dep_id having avg(age)>25); 2.查看技術部員工姓名 select name from employee where dep_id = (select id from department where name = '技術'); 3.查看不足1人的部門名(子查詢獲得的是有人的部門id) 在員工表中不存在的一個部門id,在department表裏 在department表裏的id字段中找到一個在員工表的dep_id中不存在的項 select name from department where id not in (select dep_id from employee group by dep_id); 把員工表裏全部的人所在的dep_id都查出來 子查詢

1.查詢大於全部人平均年齡的員工名與年齡 select avg(age) from employee; select name,age from employee where age > (select avg(age) from employee); 2.查詢大於部門內平均年齡的員工名、年齡 select dep_id,avg(age) from employee group by dep_id; select * from employee inner join (select dep_id,avg(age) as avg_age from employee group by dep_id) as t2 on employee.dep_id = t2.dep_id where employee.age > t2.avg_age; 帶比較的子查詢