【问题标题】:MySQL Selecting ID's that are not in another tableMySQL 选择不在另一个表中的 ID
【发布时间】:2015-03-01 03:26:22
【问题描述】:

我正在尝试编写一个查询,该查询从项目列表中选择两个 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 完成,还是我必须一遍又一遍地循环查询,直到返回结果?

【问题讨论】:

    标签: php mysql sql


    【解决方案1】:

    您应该返回一行,其中包含两个尚未面对面的项目。编写查询的简单方法是:

    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;
    

    【讨论】:

      猜你喜欢
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 2018-03-20
      • 2016-01-27
      • 2012-07-30
      • 1970-01-01
      相关资源
      最近更新 更多