Output MySQL list of records, grouped by category?

心已入冬 提交于 2019-12-08 03:52:27

问题


I have data like this:

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

And I'd like to get this output:

Mustards
Hot Mustard
Horseradish Mustard
Honey Mustard

Sauces
Tomato Sauce
Barbeque Sauce

I thought I could do it with GROUP BY and/or DISTINCT, like this:

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

but I'm not having much luck. Can anyone help?

Thanks - Joe


回答1:


Try this:

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

Output:

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

See this SQLFiddle



来源:https://stackoverflow.com/questions/11928360/output-mysql-list-of-records-grouped-by-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!