使用子查询选择 varchar(30) 的'select not in'查询



我是SQL Server的新手,正在尝试使用SQL Server为以下场景创建查询。

我有一个名为GenericLabels的表,其中包含可以使用的所有标签(varchar(30))的列表。它们用于名为UserDeviceStatus的表中。我想要在给定UserIdGenericLabels中但在UserDeviceStatus中未使用的标签列表。

我创建了以下查询

select label 
from GenericLabels 
where not exists (select customlabel from UserDeviceStatus where userid = 40)

此查询返回空结果

以下是带有单个查询的输出。

select label from GenericLabels

返回

Aux1
Aux2
Aux3
Aux4
Aux5
Aux6

select customlabel from userdevicestatus where userid = 40 

返回

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)
SELECT customlabel from userdevicesstatus where userid != 40

这应该会给你想要的结果。

最新更新