我创建了两个表类型和超类型,它们分别具有名称类型和类型的列。我根据Types表的不同类型创建SuperTypes表,但是当我执行以下查询时,我得到了这些结果。
mysql> select count(distinct type) from SuperTypes;
+----------------------+
| count(distinct type) |
+----------------------+
| 1302 |
+----------------------+
mysql> select count(distinct types) from Types;
+-----------------------+
| count(distinct types) |
+-----------------------+
| 1306 |
+-----------------------+
所以,我想通过以下查询知道SuperType中不存在哪些类型的Type表,但我得到的是空集而不是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)
答案 0 :(得分:2)
这种情况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
);