SQL搜索缺少两个条目之一

时间:2015-09-14 14:49:07

标签: sql-server

所有记录在“image_sub_type”列中都有多个条目。

我想搜索2个条目,“链接ltr”和“视频”,并希望所有记录都包含“link ltr”但缺少“视频”条目。

下面的查询列出了所有“link ltr”有或没有“video”的记录,但我只想要“link ltr”缺少“video”。

SELECT M.INCIDENT_ID
FROM TB_IMAGE M
JOIN TB_DIRECTORY D ON D.DIRECTORY_ID = M.DIRECTORY_ID
WHERE D.DIRECTORY_ID = 104
AND m.image_sub_type IN ('link ltr')
AND m.image_sub_type NOT IN ('video')

输出示例:

我可以得到这个:

INCIDENT_ID image_sub_type
376815      LINK LTR
397890      LINK LTR
398831      LINK LTR
398831      VIDEO
399066      LINK LTR
399443      LINK LTR
399690      LINK LTR
399690      VIDEO
401045      LINK LTR
401045      VIDEO

但我想要这个:

INCIDENT_ID image_sub_type
376815      LINK LTR
397890      LINK LTR
399066      LINK LTR
399443      LINK LTR

任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

To find all records that has 'link ltr', but not 'video', you could do two joins to the tb_directory table:

  • an inner join only link ltr records two only include records with 'link ltr'
  • a left join/is null for 'video' to only include records which does not have 'video'

Like this:

SELECT MLink.INCIDENT_ID
FROM TB_IMAGE MLink
    LEFT JOIN TB_IMAGE MVideo ON MLink.INCIDENT_ID = MVideo.INCIDENT_ID AND MVideo.image_sub_type = 'video'
    JOIN TB_DIRECTORY D ON D.DIRECTORY_ID = MLink.DIRECTORY_ID
WHERE MLink.image_sub_type IN ('link ltr') -- Records that does have link ltr ..
    AND MVideo.image_sub_type IS NULL -- .. but no matches on video left join
    AND D.DIRECTORY_ID = 104