Sample Header Ad - 728x90

LIMIT the number of rows in GROUP BY and GROUP_CONCAT with ORDER

1 vote
2 answers
6063 views
In this 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; How can I LIMIT the number of rows returned by GROUP_BY? My problem is that ORDER within GROUP_BY should be identical to ORDER within GROUP_CONCAT. For example, if using LIMIT 3, the output should be 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
Asked by Googlebot (4551 rep)
Sep 24, 2021, 12:45 AM
Last activity: Sep 24, 2021, 11:40 PM