簡體   English   中英

在group_concat中排序

[英]Sorting in group_concat

數據:

id  uid     type

1   20      A
2   20      B
3   20      A
4   6       A
5   1       A
6   3       A
7   6       A
8   1       B

場景:

我想按type分組並按id排序。 我正在使用group by來分組uid

當前查詢:

SELECT
    type,
    GROUP_CONCAT(DISTINCT uid) AS users,
    COUNT(type) AS typeCount
FROM
    `test2`
GROUP BY
    type

問題:

但是uid的順序不正確,它應該按照id降序排列。

預期結果:

type    users       typeCount
A       6,3,1,20    6
B       1,20        2

我的結果:

type    users       typeCount
A       20,6,1,3    6
B       20,1        2

MySQL的謎團。

實際上引擎以ASC順序獲取第一個值,無論你是通過ID要求DESC,所以首先“翻轉”表,然后:

SELECT
    type,
    GROUP_CONCAT(DISTINCT uid ORDER BY id DESC) AS users,
    COUNT(type) AS typeCount
FROM
    (SELECT * FROM `test2` ORDER BY id DESC) test2
GROUP BY
    type

SQLFiddleDemo

你可以做一些像Sampson在這篇文章中建議的:

MySQL:排序GROUP_CONCAT值

這是MySQL文檔的鏈接

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function%5Fgroup-concat

這是他給出的例子:

SELECT student_name,
  GROUP_CONCAT(DISTINCT test_score ORDER BY test_score DESC SEPARATOR ' ')
  FROM student
  GROUP BY student_name;

您只需根據需要進行調整即可。

希望這可以幫助

@mitkosoft的答案已經是正確的。

我發布此信息只是為了分析正確的預期結果。

從下面的輸出中,我們可以看到,對於類型'A'組,在DISTINCT生效之前,在ORDER BY id DESC之后,行是:

6 3 1 6 20 20

然后DISTINCT可以產生兩種可能的結果:6,3,1,20或3,1,6,20。

產生哪一個是未確定的並且實現相關。 否則,我們不能依賴於此。

因此,'A'組的預期結果應為6,3,1,20或3,1,6,20。 兩個都正確。

mysql> SELECT * FROM test2;
+------+------+------+
| id   | uid  | type |
+------+------+------+
|    1 |   20 | A    |
|    2 |   20 | B    |
|    3 |   20 | A    |
|    4 |    6 | A    |
|    5 |    1 | A    |
|    6 |    3 | A    |
|    7 |    6 | A    |
|    8 |    1 | B    |
+------+------+------+
8 rows in set (0.00 sec)

mysql> SELECT uid FROM test2 WHERE type='A' ORDER BY id DESC;
+------+
| uid  |
+------+
|    6 |
|    3 |
|    1 |
|    6 |
|   20 |
|   20 |
+------+
6 rows in set (0.00 sec)

嘗試類似的東西:

 SELECT
    type,
    GROUP_CONCAT(DISTINCT uid) AS users,
    COUNT(type) AS typeCount
FROM
    (SELECT type, uid
     FROM `test2`
     ORDER BY uid desc) mytableAlias
GROUP BY
    type

這不需要子查詢。 根據您的描述,您只需在GROUP_CONCAT()使用ORDER BY

SELECT type,
        GROUP_CONCAT(DISTINCT uid ORDER BY uid DESC) AS users,
        COUNT(type) AS typeCount
FROM `test2`
GROUP BY type;

在MySQL中,最好避免不必要的子查詢,因為數據庫引擎會實現它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM