子查询
在一个select语句中,又出现了其它select语句。
子查询可以出现的位置有:
- 列的部分
select
tb1.*,(select
namefrom
s_cartwhere
id
=1) vfrom
tb1 --注意,这里的子查询只能返回 一行一列 的内容。
select tb1.*,(select name from s_cart where id
=1) v from tb1 --注意,这里的子查询只能返回 一行一列 的内容。
- where的部分
-- in 条件
select
*from
tb1where
idin
(selectdistinct
tb1_idfrom
tb2)
- from 的部分
select
id,c1,c2from
(
select
tb1.*,tb2.id tb2id,tb2.c1 tb2c1,tb2.c2from
tb1
left join
tb2on
tb1.id
= tb2.tb1
_id ) t – 这种情况下,必须为表定义别名
分页查询
跟两个要素有关:
- 每页显示几条数据 : m
- 当前显示第几页 : n (从1开始)
在MySQL 语句中,提供了 limit
关键字,它接收两个参数,参数1 表示数据集的开始索引(从0开始),参数2 表示最多返回多少条结果。
select * from tb1 LIMIT (n-1)*m,m
在配合子查询,就可以实现任意结果的分页显示。
select * from (其它查询) t
LIMIT (n-1)*m,m