如何返回在MySQL中实际上是“连续的” GROUP BY的内容。换句话说,GROUP BY是否尊重记录集的顺序?
例如,SELECT MIN(col1), col2, COUNT(*) FROM table GROUP BY col2 ORDER BY col1从下表中,col1是唯一的有序索引:
SELECT MIN(col1), col2, COUNT(*) FROM table GROUP BY col2 ORDER BY col1
1个 2个 3分 4例 5个 6个
返回:
1一4 3 b 2
但我需要返回以下内容:
1一2 3 b 2 5 2
使用:
SELECT MIN(t.id) 'mi', t.val, COUNT(*) FROM (SELECT x.id, x.val, CASE WHEN xt.val IS NULL OR xt.val != x.val THEN @rownum := @rownum+1 ELSE @rownum END AS grp FROM TABLE x JOIN (SELECT @rownum := 0) r LEFT JOIN (SELECT t.id +1 'id', t.val FROM TABLE t) xt ON xt.id = x.id) t GROUP BY t.val, t.grp ORDER BY mi
这里的关键是创建一个允许分组的人为值。
以前,更正了Guffa的答案:
SELECT t.id, t.val FROM TABLE t LEFT JOIN TABLE t2 on t2.id + 1 = t.id WHERE t2.val IS NULL OR t.val <> t2.val