mySQL命令由count子查询引起的麻烦

时间:2012-08-10 15:29:23

标签: mysql count subquery

我有一个名为items_status的表,它有3个字段,item_id,user_id和status,可以是'have'或'want'。

Field   Type                Null    Key 
user_id varchar(10)         NO      PRI     
item_id varchar(10)         NO      PRI     
status  set('have','want')  YES     NULL

我有一个页面,我希望获得表格中所有用户ID的列表,这些用户id按状态为“have”的表中的用户ID所关联的记录数排序。到目前为止,这是我能想到的最好的:

SELECT user_id 
FROM items_status AS is  
ORDER BY 
    //Subquery to get number of items had by user
    (SELECT COUNT(i.item_id) 
          FROM items_status AS i 
          WHERE i.user_id = is.user_id AND i.status = 'have') DESC
GROUP BY user_id 

但是,这会在子查询上引发错误。如何按表中的项目数量排列表中的所有用户ID?

2 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT  user_id
FROM    items_status
WHERE   `status` = 'have'
GROUP BY userID
ORDER BY COUNT(user_id) DESC

SQLFiddle Demo

,列名略有不同,但查询相同

答案 1 :(得分:0)

SELECT user_id, SUM(CASE WHEN i.status = 'have' THEN 1 ELSE 0) AS s
FROM items_status AS is
GROUP BY user_id
ORDER BY  SUM(CASE WHEN i.status = 'have' THEN 1 ELSE 0) DESC