输出MySQL记录列表,按类别分组?

时间:2012-08-13 04:54:13

标签: mysql group-by distinct

我有这样的数据:

Category     Product
Mustards     Hot Mustard
Mustards     Horseradish Mustard
Mustards     Honey Mustard
Sauces       Tomato Sauce
Sauces       Barbeque Sauce

我想得到这个输出:

Mustards
Hot Mustard
Horseradish Mustard
Honey Mustard

Sauces
Tomato Sauce
Barbeque Sauce

我以为我可以用GROUP BY和/或DISTINCT来做,像这样:

    SELECT DISTINCT category, prodName
    FROM recipes
    GROUP BY category
    ORDER BY category, prodName ASC

但我运气不好。有人可以帮忙吗?

谢谢 - 乔

1 个答案:

答案 0 :(得分:4)

试试这个:

SELECT category, GROUP_CONCAT(ProdName) as Product
FROM recipes
GROUP BY category
ORDER BY category, ProdName ASC

<强>输出:

CATEGORY     PRODUCT
----------------------------------------------------------
Mustards     Hot Mustard,Horseradish Mustard,Honey Mustard
Sauces       Tomato Sauce,Barbeque Sauce

See this SQLFiddle