选择只有一行且该行是特定值的ID

时间:2019-03-15 14:38:38

标签: sql sql-server-2016

我有这个查询。有很多联接,因为我正在检查ID是否链接到任何这些表。

当前,此查询向我显示未链接到任何这些表的任何ID。我想对其进行添加,以便它还显示链接到d表的所有ID,但前提是D表中只有1行并且D字段中的类型为“ member”。

SELECT 
    c.ID,
    c.location,
    c.pb,
    c.name,
    c.surname

FROM c
    LEFT JOIN l on c.rowno = l.rowno
    LEFT JOIN d on c.rowno = d.rowno
    LEFT JOIN t on c.rowno = t.rowno
    LEFT JOIN cj ON (c.rowno = cj.rowno OR c.rowno = cj.rowno2)
    LEFT JOIN dj ON c.rowno = d.rowno
    LEFT JOIN lg ON c.rowno = lg.rowno
    LEFT JOIN tj ON c.rowno = tj.rowno

WHERE
    c.status != 'closed'
    AND l.rowno IS NULL
    AND d.rowno IS NULL
    AND t.rowno IS NULL
    AND cj.rowno IS NULL
    AND dj.rowno IS NULL
    AND lg.rowno IS NULL
    AND tj.rowno IS NULL

我首先想到的是添加

WHERE D.type = 'member'

但是,这给了我所有具有D.type =成员行的ID(它们可以有10行具有所有不同类型的行,但是只要其中的1个具有type = member的行就会显示)。我想看到只有d.type = member

的ID

很抱歉,我的措词不好,我很难直截了当地说这句话。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:1)

exists表上的条件外,我将对所有条件使用D

SELECT c.*
FROM c JOIN
     (SELECT d.rownum, COUNT(*) as cnt,
             SUM(CASE WHEN d.type = 'Member' THEN 1 ELSE 0 END)  as num_members
      FROM t
      GROUP BY d.rownum
     ) d
     ON c.rownum = d.rownum
WHERE c.status <> 'closed' AND          
      NOT EXISTS (SELECT 1 FROM t WHERE c.rowno = t.rowno) AND
      NOT EXISTS (SELECT 1 FROM l WHERE c.rowno = l.rowno) AND
      . . . 

我发现NOT EXISTS在逻辑上比较容易理解。我认为SQL Server中的两种方法之间没有很大的性能差异。