[英]MySQL Selecting ID's that are not in another table
我正在尝试编写一个查询,该查询从项目列表中选择两个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;
这可能对您有用。 但是,表演可能很糟糕。 以下是一种可能具有更好性能的方法,因为它首先选择了一个随机项。 缺点是随机可能会遇到其他所有问题,因此它可能不会返回任何东西。 您可以再次调用它:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.