MySQL的特殊查询
Mysql独有的limit
1 | select * from tableName limit i,n |
使用limit
去实现TOP k问题
1 | SELECT * FROM 表 order by 字段 desc limit k; |
举个例子:
1 | # 1、查询蓝框内容,就是前三条 |
连接查询
有四种连接
- 左外连接
left join
- 右外连接
right join
- 内连接
inner join
- 全连接
UNION
(注意,和Oracle不同的!)
区别要记住:
- 左外连接中优先匹配左表,右表没有的显示为null
- 右外连接是,右表全部有,左表可能为空;
- 内连接中均不能为空;
- 全连接都会匹配;
基本语句为select xxxx from x1 left join x2 on x1.xx = x2.xx;
(即记住表1 left join 表2 on 条件
)
优点枯燥,这里用栗子解释一下:
1 | select ql_article.uid, ql_user.username |
结果:
全连接的语句有点特殊:
1 | select uid, null |
注意:
UNION左右两个查询的列个数必须一样
如果要排序请写在外面:
1
2
3
4
5(select id,name from A order by id) union all (select id,name from B order by id);
#没有排序效果
(select id,name from A ) union all (select id,name from B ) order by id;
#有排序效果