我有一个名为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?
答案 0 :(得分:2)
SELECT user_id
FROM items_status
WHERE `status` = 'have'
GROUP BY userID
ORDER BY COUNT(user_id) DESC
,列名略有不同,但查询相同
答案 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