MySQL数据库之多表查询

一.多表连接查询

#重点:外链接语法
SELECT 字段列表
    FROM 表1 INNER|LEFT|RIGHT JOIN 表2
    ON 表1.字段 = 表2.字段;

1.交叉连接叉连接:不适用任何匹配条件。生成笛卡尔积

 语法:mysql>select * from table1,table2;

2.内连接:找两张表共有的部分,相当于利用条件从笛卡尔积结果中筛选出了正确的结果

3 .外链接之左连接:优先显示左表全部记录

   本质就是:在内连接的基础上增加左边有右边没有的结果

4 .外链接之右连接:优先显示右表全部记录

   本质就是:在内连接的基础上增加右边有左边没有的结果

5. 全外连接:显示左右两个表全部记录

   全外连接:在内连接的基础上增加左边有右边没有的和右边有左边没有的结果

   注意:mysql不支持全外连接 full JOIN

运用实例:

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

#注意 union与union all的区别:union会去掉相同的纪录

二.符合条件连接查询

#示例1:以内连接的方式查询employee和department表,并且employee表中的age字段值必须大于25,即找出公司所有部门中年龄大于25岁的员工
select employee.name,employee.age from employee,department
    where employee.dep_id = department.id
    and age > 25;

#示例2:以内连接的方式查询employee和department表,并且以age字段的升序方式显示
select employee.id,employee.name,employee.age,department.name from employee,department
    where employee.dep_id = department.id
    and age > 25
    order by age asc;

三.子查询

#1:子查询是将一个查询语句嵌套在另一个查询语句中。
#2:内层查询语句的查询结果,可以为外层查询语句提供查询条件。
#3:子查询中可以包含:IN、NOT IN、ANY、ALL、EXISTS 和 NOT EXISTS等关键字
#4:还可以包含比较运算符:= 、 !=、> 、<等

1 .带IN关键字的子查询

查询employee表,但dep_id必须在department表中出现过
select * from employee
    where dep_id in
        (select id from department);

2 .带比较运算符的子查询

#比较运算符:=、!=、>、>=、<、<=、<>
#查询平均年龄在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 in 
        (select dep_id from employee group by dep_id having count(id) <=1);

3. 带EXISTS关键字的子查询

EXISTS关字键字表示存在。在使用EXISTS关键字时,内层查询语句不返回查询的记录。
而是返回一个真假值。True或False
当返回True时,外层查询语句将进行查询;当返回值为False时,外层查询语句不进行查询

#示例
mysql> select * from employee
    ->     where exists
    ->         (select id from department where id=204);
Empty set (0.00 sec)

四.sql逻辑查询语句的执行顺序

1.SELECT语句关键字的定义顺序

SELECT DISTINCT <select_list>
FROM <left_table>
<join_type> JOIN <right_table>
ON <join_condition>
WHERE <where_condition>
GROUP BY <group_by_list>
HAVING <having_condition>
ORDER BY <order_by_condition>
LIMIT <limit_number>

2. SELECT语句关键字的执行顺序

(7)     SELECT 
(8)     DISTINCT <select_list>
(1)     FROM <left_table>
(3)     <join_type> JOIN <right_table>
(2)     ON <join_condition>
(4)     WHERE <where_condition>
(5)     GROUP BY <group_by_list>
(6)     HAVING <having_condition>
(9)     ORDER BY <order_by_condition>
(10)    LIMIT <limit_number>
原文地址:https://www.cnblogs.com/sxh-myblogs/p/7501747.html