0

我有一个名为 items_status 的表,它有 3 个字段,item_id、user_id 和状态,可以是“拥有”或“想要”。

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

我有一个页面,我想在其中获取表中所有用户 ID 的列表,这些用户 ID 按状态为“拥有”的表中与其用户 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?

4

2 回答 2

2

你可以这样做:

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

SQLFiddle 演示

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

于 2012-08-10T15:33:02.763 回答
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 
于 2012-08-10T15:34:07.580 回答