需要有关如何在单个MySQL查询中执行此操作的建议

时间:2010-02-01 11:43:10

标签: mysql

这可以在一个MySQL查询中执行此操作吗?基本上我需要根据用户的响应数对用户进行排序。我有2张桌子

table "users":
id      username
------------------
1       hunter
2       loserville

和另一个

table "responses":
id      user_id     response
-------------------------------
1         1            yes
1         2            yes
1         1            no
1         1            yes

我需要这样的东西

SELECT users.id
FROM users
    UNION ALL 
        SELECT COUNT(responses.id) As num_responses
        FROM responses
        WHERE user_id = users.id
ORDER BY num_responses DESC

不幸的是它不起作用。有什么建议?如果你感到困惑,请告诉我!谢谢你的时间。

3 个答案:

答案 0 :(得分:3)

SELECT users.id, users.username, count(*) as responses
FROM   users LEFT JOIN responses
       ON users.Id = responses.user_id
GROUP BY users.id, users.username
ORDER BY count(*) DESC

答案 1 :(得分:1)

SELECT  u.id, COUNT(r.id) AS cnt
FROM    users u
LEFT JOIN
        responses r
ON      r.user_id = u.id
        AND r.response = 'yes'
GROUP BY
        u.id
ORDER BY
        cnt DESC

或者这个:

SELECT  u.id,
        (
        SELECT  COUNT(*)
        FROM    responses r
        WHERE   r.user_id = u.id
                AND r.response = 'yes'
        ) cnt
FROM    users u
ORDER BY
        cnt DESC

前者通常在InnoDB更快,后者在MyISAM

答案 2 :(得分:0)

我猜你想要使用的是GROUP BY子句。

您需要像

这样的查询
SELECT users.id, COUNT(*) AS responses 
    FROM users JOIN responses ON users.id = responses.user_id 
    GROUP BY user_id ORDER BY responses DESC

(如果您不想要来自users表的任何信息,可以省略JOIN并仅对回复进行查询。

联接会列出所有用户及其回复,然后计算条目数。