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

时间:2013-08-08 23:35:16

标签: sql sql-server

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

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

我创建了以下查询

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

3 个答案:

答案 0 :(得分:4)

您必须链接标签和customlabel:

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

答案 1 :(得分:2)

请改为尝试:

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

答案 2 :(得分:-1)

SELECT customlabel from userdevicesstatus where userid != 40

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

相关问题