MySQL多表查詢

建表和數據準備

# 建表
create table department(id int, name varchar(20));
create table employee(id int primary key auto_increment, name varchar(20), sex enum("male", "female") not null default "male", age int, dep_id int);

# 寫入數據
insert into department values (200, "技術"), (201, "銷售"), (202, "運營");

insert into employee (name, sex, age, dep_id) values 
("haha", "male", 24, 201),
("hax", "male", 24, 201),
("sax", "male", 24, 202),
("sexy", "male", 24, 200),
("proxy", "male", 24, 201);
建表,準備數據

外鏈接語法

  select 字段列表 from 表1 inner | left | right join 表2 on 表1.字段=表2.字段mysql

交叉鏈接

  直接將兩張表拼接在一塊兒,不使用任何匹配條件,生成笛卡爾積;sql

  select * from department, employee;ide

內鏈接:inner join

  找到兩張表共有的部分,至關於利用條件在笛卡爾積中篩選出了正確的結果;spa

  select employee.id employee.name employee.age from employee inner join department on employee.dep_id=department.id;code

  select employee.id employee.name employee.age from employee, department where employee.dep_id=department.id;blog

  這兩條SQL語句的效果是等同的;rem

左外鏈接:left join

  優先顯示左表的所有記錄,以左表爲準,找出全部員工信息,也包括沒有部門的員工信息;本質就是在內鏈接的基礎上增長左邊有右邊沒有的結果;io

  select employee.id, employee.name, department.name as depart_name from employee left join department on employee.dep_id=department.id;event

右外鏈接:right join

  優先顯示右表的所有記錄,以右表爲準;table

  select employee.id, employee.name, department.name as depart_name from employee right join department on employee.dep_id=department.id;

全外鏈接

  在內鏈接的基礎上增長左表有右表沒有的和右表有左表沒有的結果;mysql不支持全外鏈接full join;但能夠用下面的方式實現全外鏈接,也就是用union鏈接上左鏈接和右鏈接

  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;

子查詢

  子查詢是將一個查詢語句嵌套在另外一個查詢語句中,內層查詢語句的結果能夠做爲外層查詢語句的查詢條件;在子查詢中能夠包含:in、not in、any、all、exists、not exists等關鍵字,還能夠包含 =、!=、>、<等比較運算符;

帶in關鍵字的子查詢

# 查詢平均年齡在25歲以上的部門名
select id, 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 in
(select id from department where name="技術"); # 查看不足1人的部門名稱 select name from department where id not in (select distinct dep_id from employee);

帶比較運算符的子查詢

# 查詢 大於 全部人平均年齡的員工名與年齡
select name,age from employee where age > (select avg(age) from employee);

# 查詢 大於 部門內平均年齡的員工名、年齡
select t1.name, t1.age from employee t1 
inner join
(select dep_id, avg(age) avg_age from employee group by dep_id) t2
on t1.dep_id=t2.dep_id where t1.age > t2.avg_age;

帶exists關鍵字的子查詢

  exists關鍵字表示存在,使用exists關鍵字時,內層查詢不返回查詢的記錄,而是返回一個True或者False;返回True時,外層查詢語句將會進行查詢;返回值爲False時,外層查詢語句不進行查詢;

# 存在id爲200的部門,True;能夠查詢出結果
select * from employee where exists (select id from department where id=200);
# 不存在id爲204的部門,False;
select * from employee where exists (select id from department where id=204);
# 查詢結果爲empty
相關文章
相關標籤/搜索