GROUP BY和ORDER BY问题
问题描述:
我有以下查询:GROUP BY和ORDER BY问题
SELECT DISTINCT (
s.styleTitle
), COUNT(p.id) AS `PictureCount`
FROM `style` s
LEFT JOIN `instagram_picture_style` ps ON s.id = ps.style_id
LEFT JOIN `instagram_shop_picture` p ON ps.picture_id = p.id
LEFT JOIN `instagram_picture_category` c ON c.picture_id = p.id
LEFT JOIN `instagram_second_level_category` sl ON c.second_level_category_id = sl.id
WHERE sl.id =25
GROUP BY p.id
ORDER BY PictureCount
但此查询给我:
我基本上希望该列表由具有风格订购它中的大部分图片。我做错了什么?为什么它给我所有的风格1,我很确定它有更多的风格的图片
答
ORDER BY
没有下划线。但同样重要的是,您使用DISTINCT
的方式似乎认为它是一种功能。不是这样。它是在SELECT
上修改的,它适用于所有列。
你应该group by
你有不同的列。事情是这样的:
SELECT s.styleTitle, COUNT(p.id) AS `PictureCount`
FROM `style` s
LEFT JOIN `instagram_picture_style` ps ON s.id = ps.style_id
LEFT JOIN `instagram_shop_picture` p ON ps.picture_id = p.id
LEFT JOIN `instagram_picture_category` c ON c.picture_id = p.id
LEFT JOIN `instagram_second_level_category` sl ON c.second_level_category_id = sl.id
WHERE sl.id = 25
GROUP BY s.styleTitle
ORDER BY PictureCount DESC;
事实上,你几乎不必distinct
与group by
。如果你正在使用,你需要考虑为什么它是必要的。