笛卡儿积(两个结果的乘积)
多表查询之内连接
前提条件:两个表之间有联系,通过外键关联
1.普通内连接 语法:关键字 ... inner join ... on 条件;
在inner join关键字之前写表1
在inner join关键字之后写表2
on的后面写条件(表1是dept,表2是emp) dept.id = emp.no
语句示例:select * from dept inner join emp on dept.id = emp.no;
2.隐式内连接(用的最多) 语法:select ... from 表1,表2 where 表1.字段 = 表2.字段;
语句示例: select * from dept,emp where dept.id=emp.no;
别名: select * from dept d,emp e where d.id=e.no;
多表查询之外连接(outer关键字可以省略)
1.左外连接(左连接) 语法: select ...表1 left outer join 表2 on 表1.字段 = 表2.字段
语句示例:select * from dept left outer join emp on dept.id = emp.no;
特点:看左表,默认把左表中的全部数据都查询出来,在查询出右表中有关联的数据
2.右外连接(右连接) 语法: select ...表1 right outer join 表2 on 表1.字段 = 表2.字段
语句示例:select * from dept right outer join emp on dept.id = emp.no;
特点:看右表,默认把右表中的全部数据都查询出来,在查询出左表中有关联的数据
多表查询的总结
如果两个表中的数据都没有多余,则以下四种查询方式结果相同
1.普通内连接查询
select * from A inner join B on 条件;
2.隐式内连接查询
select * from A,B where 条件;
3.左外连接查询
select * from A left join B on 条件;
4.右外连接查询
select * from A right join B on 条件;
子查询
在sql语句中,select 。。 from 。。 作为一个查询块,将一个查询块嵌套在另一个查询块中作为条件成为嵌套查询或者子查询
语法: select * from table where 条件 >(select 字段 from table where 条件)
子查询的常用运算符
< 小于 > 大于 <= 小于等于 >= 大于等于 = 等于 <>或!= 不等于 in范围
any(任意一个)或者all(所有) >any 大于子查询中的最小值 >all 大于子查询中的最大值
语法:select * from table where 条件 >any(select 列名 from table where 条件)