1、连接查询
笛卡尔乘积现象:两个表进行连接,没有给定条件,造成m*n的情况
原因:没有有效的连接条件
eg:SELECT name,boyname
from beauty,boys
where beauty.boyid=boys.id;
2、分类
按年代分类:
sq92标准
sq99标准
按功能分类:
内连接:
(1)等值连接
eg:SELECT name,boyname
from beauty,boys
where beauty.boyid=boys.id; (相等的)
(2)非等值连接
不是=
(3)自连接
自己连接自己
外连接:
外连接的查询结果为主表中的所有记录,
如果从表中有和它匹配的,则显示匹配的值
如果从表中没有和它匹配的,则显示null
可在格式后面再加条件where,group by等
(1)左外连接(以左表为基准关联右表中的数据)
格式:select * from 表1 别名 left 【outer】join 表2 别名 on 连接条件
left左边为主表
(2)右外连接(以右表为基准关联左表中的数据)
格式:select * from 表1 别名 right 【outer】join 表2 别名 on 连接条件
right右边为主表
(3)全外连接: 两表的全集
格式:select * from 表1 别名 full【outer】join 表2 别名 on 连接条件
不支持,结果为:交集,主表有从表没有,从表有主表没有三部分
(4)内连接:两表的交集
格式:select * from 表1 别名 inner join 表2 别名 on 连接条件
注意:
关联条件可写可不写
如果不写可以写为select * from 表1,表2 where 子句;
交叉连接:cross
两表进行笛卡尔乘积
3、联合查询
union:结果集进行合并(纵向合并)
格式:
查询语句 union 查询语句
注意:
查询列数必须相同
字段为第一个sql语句的字段
union默认去重
union all不去重
4、经典例题
一张student表,一张score表,求男女生分组总分的前三名
– 求score表分组男女的各个学生的总分数
SELECT SUM(score) score,studentid
from score GROUP BY studentid;
– 2张表进行连接,求出每个学生的信息,总成绩
SELECT * from student LEFT JOIN
(SELECT SUM(score) score,studentid
from score GROUP BY studentid) as score on
student.id=score.studentid;
– 求TopN,就是之前写的TopN,只不过,将第二步的表作为表有点长而已
SELECT * from (SELECT * from student LEFT JOIN
(SELECT SUM(score) score,studentid
from score GROUP BY studentid) as score on
student.id=score.studentid) as s1
WHERE 3>(
SELECT COUNT(*) from (SELECT * from student LEFT JOIN
(SELECT SUM(score) score,studentid
from score GROUP BY studentid) as score on
student.id=score.studentid) as s2
WHERE s1.sex=s2.sex
and s1.age<s2.age
);