如何通过另一个表的计数来订购MySQL结果?

时间:2016-09-01 09:34:22

标签: mysql database

我有一个包含游戏条目的数据库表:

--------------------------------------------------------
| game_id | title  | description | entry_time          |
--------------------------------------------------------
| 1       | Game 1 | Descript... | yyyy-mm-dd hh:mm:ss |
--------------------------------------------------------
| 2       | Game 2 | Descript... | yyyy-mm-dd hh:mm:ss |
--------------------------------------------------------

另一个包含游戏历史:

-----------------------------------------------
| game_id | user_id     | entry_time          |
-----------------------------------------------
| 1       | 0da89sadf89 | yyyy-mm-dd hh:mm:ss |
-----------------------------------------------
| 1       | f8jsf89vjs9 | yyyy-mm-dd hh:mm:ss |
-----------------------------------------------
| 2       | f8jsf89vjs9 | yyyy-mm-dd hh:mm:ss |
-----------------------------------------------

我试图根据游戏的受欢迎程度从第一张桌子中选择结果。

SELECT games.game_id, games.title, games.description
  FROM `games`
  JOIN foo_db.game_plays game_plays
    ON game_plays.game_id LIKE games.game_id
  WHERE games.title LIKE "%game%"
  ORDER BY COUNT(game_plays.game_id) DESC, games.entry_time DESC
  LIMIT 10

但由于某种原因,只返回一个结果("游戏1和#34;)。

当我删除JOIN,并按entry_time排序结果时,两个结果都会按预期返回。

2 个答案:

答案 0 :(得分:1)

我做了这个查询。你可以试试吗。

SELECT a.game_id, a.title, a.description, b.total
  from games a
  JOIN (SELECT game_id, count(user_id) as total from
           game_play group by game_id) b
  ON a.game_id = b.game_id
  AND a.title LIKE '%Game%'
  ORDER BY b.total DESC, a.entry time DESC 

<强>输出

Click Here

希望它会有所帮助。

答案 1 :(得分:1)

因为在混合JOINGROUP BY时MySQL有时非常慢,所以核心子查询可能是一个不错的选择:

SELECT games.game_id, games.title, games.description
FROM `games`
WHERE games.title LIKE "%game%"
ORDER BY (
    SELECT COUNT(game_plays.game_id)
    FROM foo_db.game_plays
    WHERE game_plays.game_id = games.game_id
) DESC, games.entry_time DESC
LIMIT 10