SQL GROUP BY多个字段

时间:2014-06-29 12:53:54

标签: mysql sql

我有以下SQL语句:

SELECT COUNT(r.id) as ratings_count, AVG(r.rating) as average_rating, b.id, b.bpm, b.producer, b.name, 
    (SELECT p.price FROM beats_pricing as p WHERE p.license = 1 AND p.beat_id = b.id) as price_1,
    (SELECT p.price FROM beats_pricing as p WHERE p.license = 2 AND p.beat_id = b.id) as price_2
    FROM beat_ratings AS r
    INNER JOIN beats AS b
    ON b.id = r.beat_id
    WHERE b.active = 1
    GROUP BY r.beat_id
    HAVING price_1 > 0
    ORDER BY average_rating DESC, ratings_count DESC
    LIMIT 50

我有一张beats的表格,beat_ratings中的每个节拍都有多行,这是一个单独的5星评级表。此SQL语句用于获得评分最高的beats。我还按r.beat_id进行分组,以确保每个beat只返回一行。

每个节拍都有b.producer,我只想为每个beat返回一个producer。我已尝试将其添加到GROUP BY

GROUP BY r.beat_id, b.producer

但是这会返回完全相同的结果。如何根据b.producer字段分组或仅返回唯一的行?

1 个答案:

答案 0 :(得分:2)

您需要将查询移动到子查询中,然后按生产者分组:

SELECT *
FROM (yourquery)
GROUP BY producer