MySQL 中 NOT EXIST 的查询不是 return 预期结果

Query with NOT EXIST in MySQL does not return expected result

我创建了两个 tables 类型和超类型,它们分别具有名称类型和类型的列。我根据类型 table 的不同类型创建了 SuperTypes table 但是当我执行以下查询时我得到了这些结果。

mysql> select count(distinct type) from SuperTypes;
+----------------------+
| count(distinct type) |
+----------------------+
|                 1302 |
+----------------------+



mysql> select count(distinct types) from Types;
+-----------------------+
| count(distinct types) |
+-----------------------+
|                  1306 |
+-----------------------+

因此,我想通过以下查询了解 SuperType 中不存在哪些类型的类型 table,但我得到的是空集而不是 4 种类型。

我该如何解决这个问题?

mysql> select distinct types from Types where not exists 
(select distinct type from SuperTypes,Types where SuperTypes.type=Types.types);

Empty set (0.00 sec)

这种情况 NOT IN 可能更适合,请尝试以下操作:

select distinct types 
from Types 
where types not in 
(
   select distinct type 
   from SuperTypes
)
;

或者您可以加入:

   select distinct t.types 
   from Types t
   left join SuperTypes st
   on st.type = t.types
   where st.type is null;

此外,您的查询不起作用的原因是您的子查询引用了它自己的列,如果您将查询更改为以下内容,它应该也能正常工作:

select distinct t1.types 
from Types t1
where not exists 
(
   select distinct st.type 
   from SuperTypes st, Types t2 
   where st.type = t1.types
);

子查询需要引用回父查询以了解要匹配的内容。其中,您真的根本不需要在子查询中加入:

select distinct t1.types 
from Types t1
where not exists 
(
   select distinct st.type 
   from SuperTypes st
   where st.type = t1.types
);