如何选择LEFT OUTER JOIN

时间:2012-02-29 20:33:28

标签: sql sql-server tsql

如何选择:选择我的表中存在的所有proposta_id,名为San_Proposta,以及我的表中存在的所有proposta_id San_Negocio当San_Negocio中的proposta_id具有ValidaCaptacao = 0 AND ValidaVenda = 1列或ValidaVenda列时= 0 AND ValidaCaptacao = 1并且San_Negocio中的Proposta_Id列不能为NULL ??

我不知道是否必须使用LEFT OUTER JOIN,但是按照我的尝试,这不能正常工作,因为我在San_Proposta.Proposta_Id中有一些在San_Negocio.Proposta_Id中不存在但是这个数据没有出现。

    SELECT San_Proposta.Proposta_Id 
    FROM San_Proposta
    LEFT OUTER JOIN San_Negocio
    ON San_Proposta.Proposta_Id = San_Negocio.Proposta_Id
    WHERE San_Negocio.Proposta_Id IS NOT NULL
    AND (San_Negocio.ValidaCaptacao = 1 AND San_Negocio.ValidaVenda = 0) 
    OR (San_Negocio.ValidaCaptacao = 0 AND San_Negocio.ValidaVenda = 1)

2 个答案:

答案 0 :(得分:4)

在WHERE子句中测试LEFT JOINed表中的列时,强制该连接的行为就像它是INNER JOIN一样。相反,将这些测试作为连接条件的一部分。您还需要删除WHERE San_Negocio.Proposta_Id IS NOT NULL,因为这也会导致INNER JOIN。

SELECT San_Proposta.Proposta_Id 
    FROM San_Proposta
        LEFT OUTER JOIN San_Negocio
            ON San_Proposta.Proposta_Id = San_Negocio.Proposta_Id
                AND (San_Negocio.ValidaCaptacao = 1 AND San_Negocio.ValidaVenda = 0) 
                 OR (San_Negocio.ValidaCaptacao = 0 AND San_Negocio.ValidaVenda = 1)

答案 1 :(得分:-1)

SELECT San_Proposta.Proposta_Id 
FROM San_Proposta
INNER JOIN San_Negocio
ON San_Proposta.Proposta_Id = San_Negocio.Proposta_Id
WHERE (San_Negocio.ValidaCaptacao = 1 AND San_Negocio.ValidaVenda = 0) 
OR (San_Negocio.ValidaCaptacao = 0 AND San_Negocio.ValidaVenda = 1)