Mysql
使用 ORDER 限制 GROUP BY 和 GROUP_CONCAT 中的行數
在這個sqlfiddle中,
CREATE TABLE t1 ( id int(11) unsigned NOT NULL, val int(11) unsigned NOT NULL, rank mediumint(7) unsigned, INDEX(id), INDEX(rank), PRIMARY KEY(id,val) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_general_ci; INSERT INTO t1 (id,val,rank) VALUES (1,2,2), (1,1,1), (1,9,1), (1,5,23), (1,3,2), (2,2,1), (2,9,8), (2,5,0); SELECT id,GROUP_CONCAT(CONCAT(val,'|',rank) ORDER BY rank DESC SEPARATOR ',') FROM t1 GROUP BY id;
如何限制返回的行數
GROUP_BY
?我的問題是
ORDER
withinGROUP_BY
應該與ORDER
within 相同GROUP_CONCAT
。例如,如果使用
LIMIT 3
,輸出應該是id GROUP_CONCAT(CONCAT(val,'|',rank) ORDER BY rank DESC SEPARATOR ',') 1 5|23,3|2,2|2 2 9|8,2|1,5|0
MariaDB 10.3
GROUP_CONCAT(... LIMIT )
( https://mariadb.com/kb/en/group_concat/ )OFFSET
也可以工作。MySQL 8.0 還沒有
LIMIT
. 請參閱 bugs.mysql.com 中的錯誤 82616 (2016)、71467、62186、30098、12544 (2005)
WITH cte AS ( SELECT *, DENSE_RANK() OVER (PARTITION BY id ORDER BY rank DESC) drnk FROM t1 ) SELECT id, GROUP_CONCAT(CONCAT(val,'|',rank) ORDER BY rank DESC SEPARATOR ',') FROM cte WHERE drnk <= 2 GROUP BY id;
https://dbfiddle.uk/?rdbms=mariadb_10.5&fiddle=ce501d92ef88b63bca30705037d19633