我想要做的是从表格中检索所有数据,并按用户在特定类别中播放的游戏数量进行排序。有什么办法可以使用某种“COUNT WHERE”sql语句吗?
这是我到目前为止所拥有的。如果他们在“fps”类别中玩过游戏,它只会返回用户,但是我希望它以降序显示所有用户,即使他们没有玩过fps游戏。请原谅我糟糕的桌子
SELECT user_data.user, COUNT(played_games.game_cat) as 'count'
FROM user_data, played_games
WHERE user_data.user_id = played_games.user_id and played_games.game_cat = 'fps'
GROUP BY user_data.user_id
ORDER BY 'count' DESC;
user_data table
user_id | user
1 | jeff
2 | herb
3 | dug
plays_games表
id | user_id | game | game_cat
1 | 2 | kill | fps
2 | 1 | shoot| fps
3 | 2 | COD | fps
4 | 3 | dogs | cas
答案 0 :(得分:2)
即使另一个表中不存在相应的记录,您也需要LEFT OUTER JOIN来获取记录。
SELECT user, coalesce(count(game_cat), 0) as count
FROM user_data LEFT OUTER JOIN played_games
ON user_data.user_id = played_games.user_id AND played_games.game_cat='fps'
GROUP BY user_data.user_id
ORDER BY count desc;
在我的屏幕上显示以下结果
+------+-------+
| user | count |
+------+-------+
| herb | 2 |
| jeff | 1 |
| dug | 0 |
+------+-------+
答案 1 :(得分:1)
试试这个:
SELECT ud.user, coalesce(sum(pg.game_cat = 'fps'), 0) Total
FROM user_data ud
LEFT JOIN played_games pg ON ud.user_id = pg.user_id
GROUP BY ud.user_id
ORDER BY Total DESC
这将显示所有用户以及他们玩“fps”类别游戏的次数。
答案 2 :(得分:1)
我就是这样做的。没有子查询,没有COALESCE,没有COUNTIF垃圾。
SELECT `users`.`user`, COUNT(`played_games`.id) AS `c`
FROM `users`
LEFT OUTER JOIN `played_games` ON
`users`.`user_id` = `played_games`.`user_id`
AND `played_games`.`game_cat` = "fps"
GROUP BY `users`.`user_id`
ORDER BY `c` DESC, `user` ASC
SQLFiddle(不确定你是否可以像这样链接他们......)
答案 3 :(得分:1)
coalesce one很有前途,但对我不起作用,感叹〜我刚发现NULLIF是解决这个问题的好方法。记得使用LEFT JOIN
COUNT( NULLIF(TABLE.ATTR, 1) ) AS total_count
TABLE.ATTR是一些可以为NULL的字段,这是一个例子:
SELECT Posts.*, COUNT( NULLIF(Comments.user_email, 1) ) as comment_num
FROM (`Posts`)
LEFT OUTER JOIN `Comments` ON `Comments`.`post_id` = `Posts`.`id`
GROUP BY `Posts`.`id`
LIMIT 5
从http://www.bennadel.com/blog/579-SQL-COUNT-NULLIF-Is-Totally-Awesome.htm
得到了这个想法答案 4 :(得分:0)
下面查询具有用户ID和按计数排序的所有游戏类别
select * from (SELECT user_data.user, COUNT(played_games.game_cat) as 'count'
FROM user_data, played_games
WHERE user_data.user_id = played_games.user_id(+) GROUP BY user_data.user_id)
order by count desc