gpt4 book ai didi

mysql - 使用复杂查询的排名系统 : more precise filters

转载 作者:行者123 更新时间:2023-11-29 01:43:42 25 4
gpt4 key购买 nike

为了在我的游戏服务器上实现排名系统,我将每个玩家的一些信息存储在 MySQL 数据库中。我有以下数据库表。

带有示例数据的表 players:

id | steamId | deaths
---+---------+-------
1 | asdja | 2
2 | kfjsl | 5

带有示例数据的武器表:

playerId | weaponId | kills
---------+----------+------
1 | 5 | 8
1 | 9 | 7
2 | 3 | 3
2 | 6 | 10
2 | 7 | 2

您看到我没有将每个玩家的杀戮存储在 players 表中,因为我可以简单地从 weapons 表中计算它。我不是很熟悉 SQL 查询,但我完成了以下查询以选择具有以下字段的简单数据集:

kills,
deaths,
kill-death-rate (kdrate),
count (maximum number of players),
rank (current ranking position, sorted by kills)

查询:

SELECT
SUM(weapons.kills) AS `kills`,
`deaths`,
(SUM(kills) / IF(deaths, deaths, 1)) AS `kdrate`,
(SELECT COUNT(*) FROM `players`) AS `count`,
(
SELECT
COUNT(*)
FROM
(
SELECT
p.id AS id2,
SUM(w.kills) AS kills2,
p.deaths AS deaths2,
p.steamId AS steamId2
FROM
weapons AS w,
players AS p
WHERE
p.id = w.playerId
GROUP BY
p.id
) AS temp
WHERE
temp.kills2 >= (
SELECT
SUM(weapons.kills) AS `kills`
FROM
`players`,
`weapons`
WHERE
players.id = weapons.playerId AND
`id` = 1
GROUP BY
`id`
)
ORDER BY
temp.kills2 DESC,
temp.deaths2 ASC,
temp.steamId2 ASC
) AS `rank`
FROM
`players`
INNER JOIN
`weapons`
ON
players.id = weapons.playerId
WHERE
`id` = 1
GROUP BY
`id`

有两个问题:

1.) 查询很糟糕。

2.) 使用给定的示例数据执行此查询会导致“相同排名”。我的意思是,两位玩家获得相同的排名,因为我认为两位玩家的杀戮数量相同。但是相反,玩家 1 应该排在第一位,因为他的死亡人数少于玩家 2。我不知道如何实现这一点。

提前致谢!

编辑:@Manueru_mx 给了我一个基本的操作方法:我根据他的回答得到了以下代码:

SELECT
id,
kills,
deaths,
kdrate,
COUNT(*) AS rank,
(SELECT COUNT(*) FROM players) AS `count`
FROM
(
SELECT
pys.id AS id,
SUM(wps.kills) AS kills,
pys.deaths AS deaths,
(SUM(wps.kills) / pys.deaths) as kdrate
FROM
players pys
INNER JOIN
weapons wps
ON
pys.id = wps.playerid
GROUP BY
pys.id
ORDER BY
2 DESC,
3,
4 ASC
) AS tmp
WHERE
id = 1

剩下的唯一问题是,rank 在这两种情况下都是 1。

最佳答案

这是我的“解决方案”。这个查询更简单但是得到你正在寻找的结果

select 
pys.steamID, SUM(wps.kills) as Kills,
SUM(pys.deaths) as Deaths,
(sum(wps.kills)/sum(pys.deaths)) as kdratio
--,COUNT(pys.steamID) as PlayersC
from players pys
inner join weapons wps on pys.id = wps.playerid
group by pys.steamID
order by 2 DESC, 3, 4 ASC

添加排名。

SELECT
id,
kills,
deaths,
kdrate,
ranking_usr as rank,
(SELECT COUNT(*) FROM players) AS `count`
FROM
(
SELECT
@row := @row + 1 AS ranking_usr
pys.id AS id,
SUM(wps.kills) AS kills,
pys.deaths AS deaths,
(SUM(wps.kills) / pys.deaths) as kdrate
FROM
players pys
INNER JOIN
weapons wps
ON
pys.id = wps.playerid
GROUP BY
pys.id
ORDER BY
2 DESC,
3,
4 ASC
) AS tmp
WHERE
id = 1

关于mysql - 使用复杂查询的排名系统 : more precise filters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12976162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com