如何使用左外部联接而不是在其中编写此查询

时间:2018-08-13 06:42:54

标签: sql sql-server

请帮助我使用左外部联接而不是不在内部

SELECT * 
FROM A 
INNER JOIN B ON A.ID = B.ID AND A.NUM = B.NUM                          
WHERE (A.XX <> '') 
  AND (A.ID = 'MM') 
  AND A.XX NOT IN (SELECT NUM    
                   FROM A   
                   WHERE ID = 'YY')
  and (A.XX  <> '') 
  AND (A.ID = 'MM') 
  AND (A.XX) NOT IN (SELECT NUM    
                     FROM C   
                     WHERE ID = 'YY')

1 个答案:

答案 0 :(得分:1)

只需执行左联接并检查联接的表是否为空(意味着未找到匹配的行)。

此查询将返回与原始查询相同的数据,而不使用NOT IN运算符:

SELECT * 
FROM A 
     INNER JOIN B ON A.ID = B.ID AND  A.NUM = B.NUM
     LEFT JOIN A2 ON A2.ID = 'YY' AND A2.NUM = A.XX
     LEFT JOIN C  ON C.ID =  'YY' AND C.NUM = A.XX
WHERE A.XX <> '' AND A.ID = 'MM' AND A2.NUM IS NULL AND
      A.XX <> '' AND A.ID = 'MM' AND C.NUM IS NULL