我对这个有点迷糊了——也许我用这个太多了以至于看不到解决方案?我有一个应用程序可以处理给定游戏每个赛季的玩家注册。我的目标是构建一个图表,显示每个节目每个赛季有多少新球员(一个节目实际上是年龄组)。
此查询是我当前用于执行任务的查询。这个想法是提取过去 5 个赛季的数据:
select
`seasons`.*,
(select COUNT(DISTINCT players.id) from `players`
where exists (
select * from `groups`
inner join `player_season` on `groups`.`id` = `player_season`.`group_id`
where `players`.`id` = `player_season`.`player_id` and
`program_id` = 2 and
`season_id` = seasons.id and
`paid` is not null and
`player_season`.`inactive` is null
) and not exists (
select * from `seasons`
inner join `player_season` on `seasons`.`id` = `player_season`.`season_id`
where `players`.`id` = `player_season`.`player_id` and
`seasons`.`id` < seasons.id
)
) as new_players
from `seasons` order by `seasons`.`id` desc limit 5
您可以在这个数据库 fiddle 上看到该查询正在运行:https://www.db-fiddle.com/f/k13fnyhecyeGoTKUJvtum9/0 .它为 seasonId 2 拉出 2 的玩家数。
当我将它投入生产时,它显示的数字太高了,似乎显然是在吸引玩家,这是不应该的。因此,我删除了动态季节并将 seasonId 硬编码为 2,我只得到 1 个玩家而不是 2 个玩家,如这个 db fiddle 所示:https://www.db-fiddle.com/f/7k998nxexxY5K85a5ppXJN/0 .对于历史上下文,这里是单季查询:
select
*
from `players`
where exists (
select *
from `groups`
inner join `player_season` on `groups`.`id` = `player_season`.`group_id`
where `players`.`id` = `player_season`.`player_id` and
`program_id` = 2 and
`season_id` = 2 and
`paid` is not null and
`player_season`.`inactive` is null
) and not exists (
select *
from `seasons`
inner join `player_season` on `seasons`.`id` = `player_season`.`season_id`
where `players`.`id` = `player_season`.`player_id` and
`seasons`.`id` < 2
)
我逐行检查了这个查询,没有发现任何可能导致这种差异的差异。两个 db-fiddles 中的示例数据完全相同。 为什么这个查询用作子查询时会产生不同的结果?
最佳答案
查询在主选择和子查询的第二个条件中使用了“季节”表两次。
使用 alias区分 2 个表引用:
select
`s1`.*,
(select COUNT(DISTINCT players.id) from `players`
where exists (
select * from `groups`
inner join `player_season` on `groups`.`id` = `player_season`.`group_id`
where `players`.`id` = `player_season`.`player_id` and
`program_id` = 2 and
`season_id` = s1.id and
`paid` is not null and
`player_season`.`inactive` is null
) and not exists (
select * from `seasons` AS s2
inner join `player_season` on `s2`.`id` = `player_season`.`season_id`
where `players`.`id` = `player_season`.`player_id` and
`s2`.`id` < s1.id
)
) as new_players
from `seasons` s1 order by `s1`.`id` desc limit 5
关于mysql - 用作子查询时产生不同结果的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55023157/