wxiao个人技术分享 wxiao的技术分享

MySQL多表查询

⚠️ 本文最后更新于2023年09月09日,已经过了628天没有更新,若内容或图片失效,请留言反馈

1.连接查询-内连接

内连接查询的是两张表交集的部分

隐式内连接

语法:
SELECT 字段列表 FROM 表1,表2 WHERE 条件 ...;


select patient.patientName,prescription.checkResult from patient,prescription 
where patient.patientid = prescription.patientID;


select a.patientName,b.checkResult 
from patient a,prescription b where a.patientid = b.patientID;

显示内连接

语法:
SELECT 字段列表 FROM 表1 [INNER]JOIN 表2 0N 连接条件 ...;

select a.patientName,b.checkResult 
from patient a inner join prescription b on a.patientid = b.patientID;


2.连接查询-外连接

左外连接

语法:
SELECT 字段列表 FROM 表1 LEFT [OUTER]JOIN 表2 0N 条件...;

相当于查询表1(左表)的所有数据 包含 表1和表2交集部分的数据

select a.*,b.checkResult from patient a left outer 
join prescription b on a.patientid = b.patientID;

select a.*,b.checkResult from patient a left 
join prescription b on a.patientid = b.patientID;

右外连接

语法:
SELECT 字段列表 FROM 表1 RIGHTI OUTER]JOIN 表2 0N 条件 ...;

相当于查询表2(右表)的所有数据 包含 表1和表2交集部分的数据

select b.*,a.patientName from patient a right outer 
join prescription b on a.patientid = b.patientID;

select b.*,a.patientName from prescription b right outer 
join patient a on a.patientid = b.patientID;


3.连接查询-自连接

自连接查询,可以是内连接查询,也可以是外连接查询

SELECT 字段列表 FROM 表A 别名A JOIN 表A 别名B ON 条 ...;


4.联合查询

语法:

SELECT 字段列表 FROM 表A
UNION [ALL]
SELECT 字段列表 FROM 表B ...;

直接合并

select * from patient where gender = '男'
union all
select * from patient where address = '北京市';

数据去重

select * from patient where gender = '男'
union
select * from patient where address = '北京市';

对于联合查询的多张表的列数必须保持一致,字段类型也需要保持一致。

union all 会将全部的数据直接合并在一起,union 会对合并之后的数据去重


5.子查询

概念:SQL语句中嵌套SELECT语句,称为嵌套查询,又称子查询

SELEC*FROM t1 WHERE column1 = ( SELECT column1 FROM t2 );

子查询外部的语句可以是INSERT / UPDATE / DELETE / SELECT 的任何一个

根据子查询结果不同,分为:

  • 标量子查询(子查询结果为单个值)
  • 列子查询(子查询结果为一列)
  • 行子查询(子查询结果为一行)
  • 表子查询(子查询结果为多行多列)

根据子查询位置,分为: WHERE之后、FROM之后、SELECT之后。

标量子查询
子查询返回的结果是单个值(数字、字符串、日期等),最简单的形式,这种子查询成为标量子查询。

常用的操作符: = <> > >= < <=

select * from patient 
where address = (select address from patient where patientName = '李思雨');

列子查询
子查询返回的结果是一列(可以是多行),这种子查询称为列子查询

常用的操作符:IN 、NOTIN 、ANY 、SOME 、ALL

select * from patient 
where patientid in (select patientid from prescription where depID = 3);

行子查询
子查询返回的结果是一行(可以是多列),这种子查询称为行子查询

常用的操作符:= 、<>、IN 、NOT IN

select address,gender from patient where patientid = 4;

select * from patient where (address,gender) = ('北京市','男')

select * from patient 
where (address,gender) = (select address,gender from patient where patientid = 4);

表子查询

子查询返回的结果是多行多列,这种子查询称为表子查询

常用的操作符:IN

By xiao On