多表查询
减少存储资源浪费,数据重复高的独立出一个表
连接类型
内连接 natural inner join using on where
自然连接 :自动找数据类型和列名一致的关联,否则进行笛卡尔关联
select * from t natural join t2;
数据类型不一致,列名一致的关联, using
select * from t join t2 using(col);
数据类型和列名不一致 on
select * from t join t2 on t.col = t2.col2;
不等的连接只能用on
select * from t join t2 on t.col >= t2.col2;
自连接 利用表别名
select * from t e join t2 w on e.col = w.col2;连接条件 >= 表的个数-1
select * from t join t2 using(col) join t3 on t3.col3 between 0 and 100;
外连接 left/join/full outer join on where
右外连接 ,右边表的数据都显示,左边如无补null
select * from t right join t2 where t.col = t2.col;
左外连接 ,左边表的数据都显示,右边如无补null
select * from t left join t2 where t.col = t2.col;
全外连接 两表只要有都要显示
select * from t full join t2 where t.col = t2.col;
附加连接条件 要加在on/where后面
select * from t full join t2 where t.col = t2.col and t.col1 = t2.col1;
交叉连接 笛卡尔乘积 要加where条件
select * from t cross join t2 where t.col = t2.col and t.col1 = t2.col1;
select * from t,t2 where t.col = t2.col and t.col1 = t2.col1;
子查询
用来查询不清楚的内容,先执行子查询里的内容.要衡量下子查询和多表查询之间的性能
select * from t where exp(>/=/in/exists..) (select col from t2 where ..);
单行子查询 : 子查询返回至多一行数据
多行子查询 : 子查询返回多行数据
子查询中不需要order by,是为了查询性能?
子查询可以用分组函数,但注意单行多行的问题
any/some 大于最小值,小于最大值
all 大于最大值,小于最小值
in/not in 相当于多个=
exists/not exists 存在,性能好