Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php MySQL选择不在另一个表中的ID_Php_Mysql_Sql - Fatal编程技术网

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

Php MySQL选择不在另一个表中的ID,php,mysql,sql,Php,Mysql,Sql,我正在尝试编写一个查询,从一个项目列表中选择两个ID,这两个ID在头对头匹配中从未见过。以前的头对头匹配存储在一个名为Face offs的表中。目的是为下一场比赛选择两个ID。它们应该是随机的,因此您可以继续运行查询,并继续返回新的随机面 项目: +----+-----------+ | ID | Item name | +----+-----------+ | 1 | trees | | 2 | plants | | 3 | animals | +----+------

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