我有一个查询,我使用相当密集的WHERE IN子句来获取与玩家相关的ID列表。
SELECT p.name,
0a.stat_value
FROM leaderheadsplayers p
LEFT JOIN leaderheadsplayersdata_alltime 0a
ON 0a.player_id = p.player_id
AND 0a.stat_type = 'kills'
WHERE p.player_id IN
(SELECT player_id
FROM
(SELECT 0a.player_id
FROM leaderheadsplayersdata_alltime 0a
WHERE 0a.stat_type = 'kills'
ORDER BY 0a.stat_value DESC LIMIT 0,
20
) 1a
)
问题在于我想通过使用FIND_IN_SET在我的最终结果中保留这些ID的顺序,而不再使用IN子句进行密集查询。 像这样:
SELECT p.name,
0a.stat_value
FROM leaderheadsplayers p
LEFT JOIN leaderheadsplayersdata_alltime 0a
ON 0a.player_id = p.player_id
AND 0a.stat_type = 'kills'
WHERE p.player_id IN
(SELECT player_id
FROM
(SELECT 0a.player_id
FROM leaderheadsplayersdata_alltime 0a
WHERE 0a.stat_type = 'kills'
ORDER BY 0a.stat_value DESC LIMIT 0,
20
) 1a
)
ORDER BY FIND_IN_SET(p.player_id, result_from_in_clause)
这是我目前的输出:
player_id | stat_value
3 | 304
5 | 507
4 | 208
这就是我想要的:
player_id | stat_value
5 | 507
3 | 304
4 | 208
答案 0 :(得分:1)
简单order by
应该能够做到:
SELECT p.name,
0a.stat_value
FROM leaderheadsplayers p
LEFT JOIN leaderheadsplayersdata_alltime 0a
ON 0a.player_id = p.player_id
AND 0a.stat_type = 'kills'
WHERE p.player_id IN
(SELECT player_id
FROM
(SELECT 0a.player_id
FROM leaderheadsplayersdata_alltime 0a
WHERE 0a.stat_type = 'kills'
ORDER BY 0a.stat_value DESC LIMIT 0,
20
) 1a
)
order by
0a.stat_value, p.player_id;