按子计数的顺序排序

时间:2015-03-05 09:34:00

标签: php mysql

我有2张桌子。 1个用于场地,1个用于评论。我正在尝试使用sql语句查询表并根据review表中的计数对结果进行排序。它还需要返回没有评论的场所,但它们应该在结果集的末尾。

我当前的SQL语句是:

SELECT * , (
    SELECT COUNT( * ) AS cnt
    FROM ratings r
    WHERE r.venue_id = v.id
    ORDER BY cnt DESC
)
FROM venues AS v
LEFT JOIN ratings AS r ON r.venue_id = v.id
WHERE v.active =  '1'
GROUP BY r.venue_id
LIMIT 20

但是,这只会返回不按递减计数顺序排列的结果......即使没有评级,也不会返回所有场地。

2 个答案:

答案 0 :(得分:2)

如果我正确理解了请求,则此查询应生成您期望的结果:

SELECT v.*, COUNT(*) AS cnt
FROM venues AS v
LEFT JOIN ratings AS r ON r.venue_id = v.id
WHERE v.active =  '1'
GROUP BY r.venue_id
ORDER BY cnt DESC

答案 1 :(得分:1)

也许你应该这样做。我希望我做对了,我没有合适的验证器。

SELECT * 
FROM venues as v LEFT JOIN (
    SELECT COUNT( * ) AS cnt, r.venue as ven_id
    FROM ratings r
    GROUP BY ven_id

) as counts
ON v.id = ven_id
WHERE v.active =  '1'
ORDER BY cnt DESC
LIMIT 20

主要区别在于我还选择了场地ID及其评论次数。所以我们有一个有序的数量内部查询中的venue_id列表。然后,您可以从场地表到子查询中的ven_id加入场地ID。我将GROUP BY移动到子查询。