使用IN运算符的相反功能进行查询

时间:2014-10-29 12:29:45

标签: sql sql-server

我有一个查询来返回目标ID 1,2或3

之一的图像名称
SELECT AI.ACCESSORY_IMAGE_NAME, P.PART_CODE, PT.PUBLISHED_TARGET_ID, PT.TARGET_NAME FROM ASS.ACCESSORY_IMAGE AI
JOIN PUB.PUBLISHED_ITEM PI ON PI.PUBLISHED_OBJECT_ID =  AI.ACCESSORY_IMAGE_ID and PI.PUBLISHED_OBJECT_TYPE = 'ACCESSORY_IMAGE'
JOIN PRD.ACCESSORY A ON A.ACCESSORY_ID = AI.ACCESSORY_ID
JOIN PRD.PART P ON P.PART_ID = A.PART_ID
JOIN PUB.PUBLISHED_TARGET PT ON PI.PUBLISHED_TARGET_ID = PT.PUBLISHED_TARGET_ID AND PT.PUBLISHED_TARGET_ID in (1,2,3)
WHERE AI.ACCESSORY_IMAGE_NAME = 'fire_ext.jpg'

在图像以目标标识1

发布时返回
ACCESSORY_IMAGE_NAME    PART_CODE           PUBLISHED_TARGET_ID     TARGET_NAME
-------------------------------------------------------------------------------
fire_ext.jpg            PZ4AC-00EF0-EU      1                       DEALER_ACCESS

但我想返回未发布图像的目标。在这种情况下,它是2和3

预期输出

ACCESSORY_IMAGE_NAME    PART_CODE           PUBLISHED_TARGET_ID     TARGET_NAME
-------------------------------------------------------------------------------
fire_ext.jpg            PZ4AC-00EF0-EU      2                       INTERNET
fire_ext.jpg            PZ4AC-00EF0-EU      3                       INTRANET

" NOT IN"当图像在目标1中发布时,运算符不会明显返回任何行。

2 个答案:

答案 0 :(得分:1)

我不确定"发布了什么"手段。如果它意味着在published_target表中,那么使用left join并检查不匹配:

SELECT AI.ACCESSORY_IMAGE_NAME, P.PART_CODE, PT.PUBLISHED_TARGET_ID, PT.TARGET_NAME FROM ASS.ACCESSORY_IMAGE AI
JOIN PUB.PUBLISHED_ITEM PI ON PI.PUBLISHED_OBJECT_ID =  AI.ACCESSORY_IMAGE_ID and PI.PUBLISHED_OBJECT_TYPE = 'ACCESSORY_IMAGE'
JOIN PRD.ACCESSORY A ON A.ACCESSORY_ID = AI.ACCESSORY_ID
JOIN PRD.PART P ON P.PART_ID = A.PART_ID
LEFT JOIN PUB.PUBLISHED_TARGET PT ON PI.PUBLISHED_TARGET_ID = PT.PUBLISHED_TARGET_ID AND PT.PUBLISHED_TARGET_ID in (1,2,3)
WHERE AI.ACCESSORY_IMAGE_NAME = 'fire_ext.jpg' and PT.PUBLISHED_TARGET_ID IS NULL;

同样的想法适用于任何表格。

答案 1 :(得分:0)

只需将上次加入更改为

即可
JOIN PUB.PUBLISHED_TARGET PT ON PI.PUBLISHED_TARGET_ID <> PT.PUBLISHED_TARGET_ID