搞了我一下午的东西,先简单说一下情况,背后本质就是mysql中sql执行顺序,这里可以参考这位大哥的博客:MySQL语句执行顺序,然后在他的基础之上,重点讲了 select 和 where 的执行不同,我画了下面的图:
然后就是根据上面的顺序,来看下面的SQL:
数据
create table group_by_test
(
id int unsigned auto_increment primary key,
`unique` tinyint null,
`index` varchar(255) null,
col varchar(255) null,
constraint `unique`
unique (`unique`)
);
INSERT INTO group_by_test (id, `unique`, `index`, col) VALUES (1, 1, '1', '1');
INSERT INTO group_by_test (id, `unique`, `index`, col) VALUES (2, 2, '2', '2');
INSERT INTO group_by_test (id, `unique`, `index`, col) VALUES (3, 3, '1', '3');
INSERT INTO group_by_test (id, `unique`, `index`, col) VALUES (4, 4, '4', '1');
索引排序
set @row_count:=0;
select id,@row_count:=@row_count+1 as cnt from group_by_test
where @row_count<=1
order by id;
结果:
这里走的是索引排序,所以才会仅得到2行数据,每扫描一行数据,@row_count
都会加1。
文件排序
set @row_count:=0;
select id,@row_count:=@row_count+1 as cnt from group_by_test
where @row_count<=1
order by col;
结果:
因为在查询阶段,where
条件一直是 0<1
,即select
语句没有执行,导致@row_count
没有增加,所以获取了所有数据。
文件排序:where执行时间验证
set @row_count:=0;
select id,@row_count:=@row_count+1 as cnt from group_by_test
where (@row_count:=@row_count+1)<=1
order by col;
结果:
如果说上面没有办法确定 是不是select
执行了4次,可以见下面这段sql:
set @row_count:=0;
select id,@row_count as cnt from group_by_test
where (@row_count:=@row_count+1)<=1
order by col;
结果: