php - MySQL 选择不在另一个表中的 ID

标签 php mysql sql

我正在尝试编写一个查询,从项目列表中选择两个 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/

相关文章:

php - 未捕获的异常 'ReflectionException',消息为 'Cannot set readonly property ezcReflectionClass::$class'

php - Symfony 4 不从 vHost 配置中获取环境变量

php - Laravel 5.4 symfony 新更新 SetTrustedProxies() 需要第二个参数

mysql - SQL查询: Current lowest price of products

MYSQL IF SELECT COUNT() 大于零 select * from table else return nothing found

mysql - Magento 和重新索引目录上的错误 1452(违反完整性约束)

c# - 处理大型 SQL 选择查询/分块读取 SQL 数据

sql server合并多个数据集不重复数据

Access 和 SQL Server 的 C# TableAdapter

php - 在 wordpress PHP 中创建提交表单