我正在尝试编写一个查询,从项目列表中选择两个 ID,这两个 ID 从未在正面匹配中相遇(之前的正面匹配存储在名为 Face-offs 的表中).目的是为下一场比赛选择两个 ID。它们应该是随机的,因此您可以继续运行查询,并继续返回新的随机对峙。
项目:
+----+-----------+
| ID | Item name |
+----+-----------+
| 1 | trees |
| 2 | plants |
| 3 | animals |
+----+-----------+
对峙:
+--------+-------+
| winner | loser |
+--------+-------+
| 1 | 2 |
| 2 | 3 |
+--------+-------+
目前,我有这个查询:
select id from items order by rand() limit 2
要选择两个随机项目 ID,但是,我不确定如何确定它们之前是否在 Face-Off 表的两个不同列中相遇。
这个查询可以只用 MySQL 完成吗,还是我必须一遍又一遍地循环查询直到返回结果?
最佳答案
你应该返回一行,其中有两个项目没有遇到面。编写查询的简单方法是:
select i1.id as id1, i2.id as id2
from items i1 cross join
items i2 left join
faceoffs f
on (f.winner = i1.id and f.loser = i2.id) or
(f.winner = i2.id and f.loser = i1.id)
where f.winner is null and i1.id <> i2.id
order by rand()
limit 1;
这可能对您有用。但是,性能可能很糟糕。以下是一种可能具有更好性能的方法,因为它首先选择一个随机项目。缺点是 random 可能会面对其他一切,所以它可能不会返回任何东西。您可以再次调用它:
select i1.id
from (select id
from items
order by rand()
limit 1
) i1 cross join
items i2 left join
faceoffs f
on (f.winner = i1.id and f.loser = i2.id) or
(f.winner = i2.id and f.loser = i1.id)
where f.winner is NULL and i1.id <> i2.id;
关于php - MySQL 选择不在另一个表中的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28785668/