我有一个赢家与输家的表格(表1),例如
+----+--------+-------+
| ID | Winner | Loser |
+----+--------+-------+
| 1 | 2 | 3 |
| 2 | 1 | 2 |
+----+--------+-------+
在项目1和项目2之间的最近一场比赛中,1胜(ID 2)。对于这个例子,我将其称为当前赢家和当前输家。
我正在尝试构建一个可以根据过去的结果推断出来的查询。
e.g。如果2> 3,则1> 2。然后我需要记录1> 3
的值我建立的查询会找到针对当前获胜者的多个推断输家。
理想的查询将返回一个"输家"的数组,我可以循环并在表中记录为推断结果。在这种情况下" 3"。
该表格将更新为:
+----+--------+-------+
| ID | Winner | Loser |
+----+--------+-------+
| 1 | 1 | 2 |
| 2 | 2 | 3 |
| 3 | 1 | 3 |
+----+--------+-------+
如果再次运行查询,它将不返回任何内容。
到目前为止我的过程是:
要获取当前失败者击败我使用的东西列表:
select * from TABLE1 where winner = 2
然后对于第二个要点,我有两个嵌套查询:
select * from TABLE1 where winner = 1 and loser = (select loser from rp_poss where winner = 2)
select * from TABLE1 where loser = 1 and winner = (select loser from rp_poss where winner = 2)
我真的无法弄清楚如何将这些放在一起,以删除我不想要的行。有人可以告诉我什么是最好的,最有效的查询例子,嵌套查询,某种加入?豌豆大脑真的很挣扎。
提前致谢
答案 0 :(得分:1)
你可以这样做,通过明确地查找某些记录(两个项目之间的匹配)并计数以查看它们是否为零。
CURRENTLOSER和CURRENTWINNER是变量或其他任何内容的占位符。
select previous.loser
from table1 previous
where previous.winner=CURRENTLOSER and (
select count(*)
from table1 ancient
where (ancient.winner=CURRENTWINNER and ancient.loser=previous.loser) or
(ancient.loser=CURRENTWINNER and ancient.winner=previous.loser)
) = 0
别名表(“来自table1 ancient”)将帮助您清楚地了解算法。
答案 1 :(得分:0)
这将为每个人和竞争对手提供一行,以及与该竞争对手的最后结果:(即,如果第1人上升到第2人并且输了,然后再次与该人对抗并获胜,此查询将1与竞争对手2 WIN展示,2人与竞争对手1 LOSE展示)。它显示了每个竞争对手相对于此人的最新结果。
http://sqlfiddle.com/#!2/823d3f/6/0
select x.person,
case when x.person <> t.winner then t.winner else t.loser end as competitor,
case when x.person = t.winner then 'WIN' else 'LOSE' end as result
from (select x.winner as person, max(y.id) as id
from (select winner from table1 union select loser from table1) x
join table1 y
on x.winner = y.winner
or x.winner = y.loser
group by x.winner) x
join table1 t
on x.person = t.winner
or x.person = t.loser
where x.id = t.id
答案 2 :(得分:0)
下面的查询将在第一次运行时为1到2之间的最新匹配插入推断的输家。第二次它不会插入任何新行。
最初,not exists
子查询有where id < current.id
来删除以前的输家,因为推断的游戏会插入&#39; future&#39; ids(在您的示例中为3),如果您再次运行查询,它会重新插入行,因此我将其更改为where id <> current.id
,这意味着它还将排除未来&#39;失败者。
insert into mytable (winner, loser)
select current.winner, previous.loser
from (select id, winner, loser
from mytable where
(winner = 1 and loser = 2)
or (winner = 2 and loser = 1)
order by id desc limit 1) current
join mytable previous
on previous.winner = current.loser
and previous.id < current.id
where not exists (select 1 from mytable
where id <> current.id
and ((winner = current.winner and loser = previous.loser)
or (winner = previous.loser and loser = current.winner)))