1
也許標題沒有很好地解釋。 我有這樣的:MySQL獲得與其他表匹配的前10項匹配
users (id, name)
-----------------------
| 1 | User 1 | US |
| 2 | User 2 | US |
| 3 | User 3 | FR |
| 4 | User 4 | IT |
| 5 | User 5 | US |
| ... | ...... | .. |
------------------------
games (game_id, user_id)
---------------
| 1 | 2 |
| 2 | 4 |
| 3 | 1 |
| 4 | 6 |
| ...| ... |
---------------
我需要的是獲得最高的國家打比賽,所以答案,如:
1 US 145 games
2 FR 25 games
3 IT 12 games
...
up to 10 results
我的解決辦法是這樣的,但它的速度太慢(有百萬條記錄)
select
distinct(user.country),
count(*) as counter
from games
inner join user on games.user_id = user.id
group by user.country
order by counter DESC
limit 10
'DISTINCT'是關鍵字,而不是函數。 'user.country'周圍的parens是不必要的。他們不影響聲明。實際上,在這個查詢中,'DISTINCT'關鍵字是不必要的,因爲有一個'GROUP BY user.country'子句。 – spencer7593
我建議您使用'EXPLAIN'來驗證查詢是否使用JOIN操作的合適索引。你可以用'EXPLAIN SELECT ...'的輸出來更新你的問題。快速回答爲MySQL提供了適當的索引,但在不知道MySQL正在做什麼的情況下給出答案是沒有意義的。 – spencer7593
每個用戶有多少遊戲?你有什麼指標在桌子上? –