Sql “选择不在”查询,子查询选择varchar(30)
我不熟悉SQL Server,正在尝试使用SQL Server为以下场景创建查询 我有一个名为GenericLabels的表,其中包含可以使用的所有标签varchar30的列表。它们在名为UserDeviceStatus的表中使用。我想要一个标签列表,这些标签位于GenericLabels中,但不用于给定用户ID的UserDeviceStatus中 我创建了以下查询Sql “选择不在”查询,子查询选择varchar(30),sql,sql-server,Sql,Sql Server,我不熟悉SQL Server,正在尝试使用SQL Server为以下场景创建查询 我有一个名为GenericLabels的表,其中包含可以使用的所有标签varchar30的列表。它们在名为UserDeviceStatus的表中使用。我想要一个标签列表,这些标签位于GenericLabels中,但不用于给定用户ID的UserDeviceStatus中 我创建了以下查询 select label from GenericLabels where not exists (select custom
select label
from GenericLabels
where not exists (select customlabel from UserDeviceStatus where userid = 40)
此查询返回空结果
下面是带有单个查询的输出
select label from GenericLabels
返回
Aux1
Aux2
Aux3
Aux4
Aux5
Aux6
Aux2
Aux3
及
返回
Aux1
Aux2
Aux3
Aux4
Aux5
Aux6
Aux2
Aux3
我想要下面的结果
Aux1
Aux4
Aux5
Aux6
您必须在标签和自定义标签上链接:
select label from GenericLabels
where not exists (
select 1 from UserDeviceStatus
where customlabel = label
and userid = 40
)
请尝试以下方法:
select label from GenericLabels where label not in (select customlabel from UserDeviceStatus where userid = 40)
这会给你想要的结果。not in的使用非常直观,但通常非常缓慢。不太直观,但更快的是,在表中的选择字段减去表中的选择字段,我听说不在的速度较慢,但我认为现代优化器通常会生成相同的执行计划,无论您是否使用存在于/中?如果有疑问,请测试它。请注意,我的大部分工作都是在一个5年以上的数据库引擎上进行的。这不完全是现代的。性能不是问题,但是如果列可以为空,“not in”可以给出令人惊讶的结果。