mySQL order by count subquery trouble

浪尽此生 提交于 2019-12-25 05:22:59

问题


I have a table called items_status which has 3 fields, item_id, user_id, and status, which can be either 'have' or 'want'.

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

I have a page where I want to get a list of all the user ids in the table ordered by the number of records their user id is associated with in the table where status is 'have'. So far, this is the best I can come up with:

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 

However, this pulls up an error on the subquery. How can I get all of the user ids in the table ordered by the number of items they have?


回答1:


you can do it like this:

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

SQLFiddle Demo

with slight difference of column name but the query is the same




回答2:


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 


来源:https://stackoverflow.com/questions/11904817/mysql-order-by-count-subquery-trouble

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!