我在排除MySQL查询中的项目时遇到问题。我想得到所有与“亚洲”无关的动物,例如

我的桌子看起来像这样。

Table 'animals'
+----+--------------+
| id | name         |
+----+--------------+
|  1 | Tiger        |
|  2 | Lion         |
|  3 | Spider       |
|  4 | Bird         |
+----+--------------+


表“大陆”

+----+--------------+
| id | name         |
+----+--------------+
|  1 | Europe       |
|  2 | Asia         |
|  3 | Africa       |
+----+--------------+


表“关系”

+----+--------+-----------+
| id | animal | continent |
+----+--------+-----------+
|  1 |      1 |         1 |
|  2 |      2 |         1 |
|  3 |      2 |         2 |
|  4 |      2 |         3 |
|  5 |      3 |         3 |
|  6 |      4 |         2 |
+----+--------+-----------+


这是我的查询的样子:

SELECT    a.`id`,
          a.`name`
FROM      a.`animals` AS a
LEFT JOIN `relations` AS r
       ON r.`animal` = a.`id`
WHERE     r.`continent` != 2
ORDER BY  a.`name` asc;


问题是,这给了我以下结果:

Lion
Spider
Tiger


问题是“狮子”与亚洲大陆(ID 2)有关,因此不应出现在结果中。您能帮我解决这个问题吗?

最佳答案

使用NOT EXISTS仅显示与亚洲大陆无关的这些动物:

select a.*
from animals a
where not exists (
  select 1
  from relations r
  join continent c on
    c.id = r.continent
  where c.name = 'Asia'
    and a.id = r.animal
)

关于mysql - 如何查找与MySQL表无关的项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52422139/

10-12 16:46
查看更多