5.8 數據庫多表查詢

多表鏈接查詢

 

交叉鏈接:

  不適用任何匹配條件。生成笛卡爾積、mysql

select * from employee1 ,department;

內鏈接:

  找兩張表共有的部分,至關於利用條件從笛卡爾積結果中篩選出了正確的結果。(只鏈接匹配的行)sql

  簡單來講: 取交集spa

select * from employee1,department where employee1.dep_id=department.id;
select * from employee1 inner join department on employee1.dep_id=department.id;

左鏈接:

  優先顯示左表所有記錄。code

  返回包括 左表 中的 全部記錄 和 右表 中 聯結字段 相等的記錄blog

#左連接:在按照on的條件取到兩張表共同部分的基礎上,保留左表的記錄
select * from employee1 left join department on department.id=employee1.dep_id;   # department(右表)  employee1(左表) 
select * from department left join employee1 on department.id=employee1.dep_id;

右連接:

  優先顯示右表所有記錄。io

  返回包括 右表 中的全部記錄 和 左表 中聯結字段相等的記錄class

#右連接:在按照on的條件取到兩張表共同部分的基礎上,保留右表的記錄
select * from employee1 right join department on department.id=employee1.dep_id;  # department(右表)  employee1(左表)
select * from department right join employee1 on department.id=employee1.dep_id;

  ps: 

    關於傻傻分不清除左右表的額外說明:基礎

      不論什麼關鍵字(left/right join)的左邊就是左表,關鍵字右邊就是右表select

    好比:nio

      a left/right b 

      a 爲左表,b 爲右表

全外鏈接:

  顯示左右兩個表的所有記錄。

  注意:mysql不支持全外鏈接 full join,可是mysql能夠使用union間接實現全外鏈接

select * from employee1 left join department on department.id=employee1.dep_id
union
select * from employee1 right join department on department.id=employee1.dep_id; 

符合條件鏈接查詢

# 示例1:之內鏈接的方式查詢employee和department表,而且employee表中的age字段值必須大於25,
# 即找出公司全部部門中年齡大於25歲的員工
select * from employee1 inner join department on employee1.dep_id=department.id and age>25;
 

# 示例2:之內鏈接的方式查詢employee和department表,而且以age字段的升序方式顯示
select * from employee1 inner join department on employee1.dep_id=department.id and age>25 order by age asc;

子查詢

#1:子查詢是將一個查詢語句嵌套在另外一個查詢語句中。
#2:內層查詢語句的查詢結果,能夠爲外層查詢語句提供查詢條件。
#3:子查詢中能夠包含:INNOT INANYALLEXISTSNOT EXISTS等關鍵字
#4:還能夠包含比較運算符:=!=><
#查詢平均年齡在25歲以上的部門名
select name from department where id in (
select dep_id from employee group by dep_id having avg(age) > 25
);

#查看技術部員工姓名
select name from employee where dep_id = (select id from department where name='技術'); #查看小於2人的部門名 select name from department where id in ( select dep_id from employee1 group by dep_id having count(id) < 2 ) union select name from department where id not in (select distinct dep_id from employee1); #提取空部門 #有人的部門 select * from department where id not in (select distinct dep_id from employee1); 或者: select name from department where id in ( select dep_id from employee1 group by dep_id having count(id) < 2 union select id from department where id not in (select distinct dep_id from employee1); );
相關文章
相關標籤/搜索