将两个SQL查询合并为一个

时间:2015-11-04 12:28:47

标签: sql sql-server-2008 expression

如果这看起来有点模糊且我的术语不正确,请原谅我。我是一名助理/初级网络工程师,具有非常有限的SQL查询经验。除此之外,这就是我正在处理的事情;

我尝试在Goldmine(CMS / CRM)中创建一个过滤器,按照下面指定的变量过滤结果。

WHERE c1.U_COMPANY > ' ' AND  c1.U_CONTACT > ' ' AND  
     (c1.U_COUNTRY <> 'SOUTH AFRICA') AND  
     (c1.U_CONTACT NOT LIKE '%MANAGER%' OR c1.U_CONTACT IS NULL) AND     
     (c1.U_KEY1 NOT LIKE '%ARCHIVE%' OR c1.U_KEY1 IS NULL) AND 
     (c1.U_KEY1 NOT LIKE '%DOCUMENT%' OR c1.U_KEY1 IS NULL) AND 
     (c1.U_KEY1 NOT LIKE '%SUPPLIER%' OR c1.U_KEY1 IS NULL) AND  
     (c1.U_KEY1 NOT LIKE '%OTHER%' OR c1.U_KEY1 IS NULL) AND
     (c1.U_KEY1 NOT LIKE '%TENANT%' OR c1.U_KEY1 IS NULL)

我需要合并以下内容,但不知道上述表达式的安全性。

SELECT C1.*
FROM FMBSM.DBO.CONTACT1 C1
INNER JOIN (
    SELECT DISTINCT ACCOUNTNO
    FROM FMBSM.DBO.CONTSUPP
    WHERE (
            CONTSUPP.RECTYPE = 'P'
            AND CONTSUPP.CONTACT = 'E-mail Address'
            )
    ) CS
    ON CS.AccountNo = C1.AccountNo
ORDER BY C1.CONTACT

非常感谢任何建议。

谢谢,

罗布

1 个答案:

答案 0 :(得分:0)

我认为最好把它放在ORDER BY之前,通常放置WHERE子句:

SELECT C1.*
FROM FMBSM.DBO.CONTACT1 C1
INNER JOIN (
    SELECT DISTINCT ACCOUNTNO
    FROM FMBSM.DBO.CONTSUPP
    WHERE (
            CONTSUPP.RECTYPE = 'P'
            AND CONTSUPP.CONTACT = 'E-mail Address'
            )
    ) CS
    ON CS.AccountNo = C1.AccountNo
WHERE c1.U_COMPANY > ' ' AND  c1.U_CONTACT > ' ' AND  
     (c1.U_COUNTRY <> 'SOUTH AFRICA') AND  
     (c1.U_CONTACT NOT LIKE '%MANAGER%' OR c1.U_CONTACT IS NULL) AND     
     (c1.U_KEY1 NOT LIKE '%ARCHIVE%' OR c1.U_KEY1 IS NULL) AND 
     (c1.U_KEY1 NOT LIKE '%DOCUMENT%' OR c1.U_KEY1 IS NULL) AND 
     (c1.U_KEY1 NOT LIKE '%SUPPLIER%' OR c1.U_KEY1 IS NULL) AND  
     (c1.U_KEY1 NOT LIKE '%OTHER%' OR c1.U_KEY1 IS NULL) AND
     (c1.U_KEY1 NOT LIKE '%TENANT%' OR c1.U_KEY1 IS NULL)
ORDER BY C1.CONTACT