gpt4 book ai didi

mysql - 复杂查询需要指导

转载 作者:行者123 更新时间:2023-11-29 00:50:45 25 4
gpt4 key购买 nike

下面是系统的一些背景知识。用户的战斗和胜利者是赢得最多回合的人。我需要帮助才能加入三个表。我有一个表 user,它存储用户信息。存储匹配信息的表 match。表 rounds 存储每场比赛每轮的获胜者,因此如果一场比赛有 5 轮,则表 rounds 将有五行用于该场比赛,并将记录每场比赛的获胜者每轮。

这是一些示例数据:表用户:(userid为主键)

userid   username
-----------------
1 Kevin
2 Sam
3 Steve
4 Matt

匹配:(id为主键。challengerchallenged都是user.userid的外键)

 id  challenger  challenged  rounds
-----------------------------------
1 2 3 3
2 1 2 1
3 2 3 3
4 2 4 1

回合:(所有字段都是主键。idmatch.id 的外键,winneruser.userid< 的外键)

 id  round  winner
------------------
1 1 2
1 2 2
1 3 3
2 1 1
3 1 2
3 2 3
3 3 2
4 1 4

我正在尝试构建一个将输出以下结果的查询:

winner  won   loser  won  
------------------------
Sam 2 Steve 1
Kevin 1 Sam 0
Sam 2 Steve 1
Matt 1 Sam 0

以上结果显示了每场比赛的赢家和输家。 won 字段分别显示获胜者和失败者在该场比赛中获胜的回合数。

有人知道如何构建上述查询吗?

最佳答案

select 
case when w1 > w2 then u1 else u2 end as winner,
case when w1 > w2 then w1 else w2 end as won,
case when w1 > w2 then u2 else u1 end as loser,
case when w1 > w2 then w2 else w1 end as won
from (
select m.id, u1.username as u1, u2.username as u2,
count(r1.winner) as w1,
count(r2.winner) as w2
from match m
join user u1 on m.challenger = u1.userid
join user u2 on m.challenged = u2.userid
join rounds r on r.id = m.id
left join rounds r1 on r.id = r1.id and r.round = r1.round and r1.winner = u1.userid
left join rounds r2 on r.id = r2.id and r.round = r2.round and r2.winner = u2.userid
group by m.id, u1.username, u2.username
) t

它依赖于(Problems with NULL Values):

Aggregate (summary) functions such as COUNT(), MIN(), and SUM() ignore NULL values.

这是一个优势。

关于mysql - 复杂查询需要指导,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8653223/

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