正文
(
select
rand
() * (
select
max
(
id
)
from
`table_name`
)
as
nid) t2
on
t1.id > t2.nid
limit
1000
;
九、区分in和exists, not in和not exists
select
*
from
表A
where
id
in
(
select
id
from
表B)
上面sql语句相当于
select
*
from
表A
where
exists
(
select
*
from
表B
where
表B.id=表A.id)
区分in和exists主要是造成了驱动顺序的改变(这是性能变化的关键),如果是exists,那么以外层表为驱动表,先被访问,如果是IN,那么先执行子查询。所以IN适合于外表大而内表小的情况;EXISTS适合于外表小而内表大的情况。
关于not in和not exists,推荐使用not exists,不仅仅是效率问题,not in可能存在逻辑问题。如何高效的写出一个替代not exists的sql语句?
原sql语句
select
colname …
from
A表
where
a.id
not
in
(
select
b.id
from
B表)
高效的sql语句
select
colname …
from
A表
Left
join
B表
on
where
a.id = b.id
where
b.id
is
null
取出的结果集如下图表示,A表不在B表中的数据
十、使用合理的分页方式以提高分页的效率