在一段查询中加上 limit 之后查询的结果顺序发生了变化
表的结构和查询语句如下
drop table if exists user;
drop table if exists grade_info;
CREATE TABLE user (
id int(4) NOT NULL,
name varchar(32) NOT NULL
);
CREATE TABLE grade_info (
user_id int(4) NOT NULL,
grade_num int(4) NOT NULL,
type varchar(32) NOT NULL
);
INSERT INTO user VALUES
(1,'tm'),
(2,'wwy'),
(3,'zk'),
(4,'qq'),
(5,'lm');
INSERT INTO grade_info VALUES
(1,3,'add'),
(2,3,'add'),
(1,1,'reduce'),
(3,3,'add'),
(4,3,'add'),
(5,3,'add'),
(3,1,'reduce');
SELECT
user_id,
u.name,
SUM(CASE
WHEN type = "reduce" THEN
- grade_num ELSE grade_num
END ) grade
FROM
grade_info g,user u
WHERE g.user_id=u.id
GROUP BY u.id,u.name
ORDER BY grade DESC
不加limit的查询结果
user_id name grade
2 wwy 3
4 qq 3
5 lm 3
1 tm 2
3 zk 2
加limit 3的查询结果
user_id name grade
2 wwy 3
5 lm 3
4 qq 3
加limit 2的查询结果
user_id name grade
5 lm 3
2 wwy 3
可以看到原本默认按照序号排序的查询结果变成了不规则乱序,希望知道的乱序的原因和解决方案