我的数据库中有一个数据,如下所示:
jamu_a | jamu_b | khasiat
A | B | Z
A | B | X
A | B | C
然后,我想要一个像这样的输出:
jamu_a | jamu_b | khasiat | total
A | B | Z,X,C | 3
最佳答案
SELECT jamu_a,jamu_b,GROUP_CONCAT(khasiat) khasiat,COUNT(*) total
FROM TableName
GROUP BY jamu_a,jamu_b
> SQLFiddle Demo
> MySQL GROUP_CONCAT()
OUTPUT
╔════════╦════════╦═════════╦═══════╗
║ JAMU_A ║ JAMU_B ║ KHASIAT ║ TOTAL ║
╠════════╬════════╬═════════╬═══════╣
║ A ║ B ║ Z,C ║ 3 ║
╚════════╩════════╩═════════╩═══════╝
如果列KHASIAT上有重复值并且您希望它是唯一的,则可以在GROUP_CONCAT()上添加DISTINCT
SELECT jamu_a,GROUP_CONCAT(DISTINCT khasiat) khasiat,jamu_b