sql left join使用left join获取匹配的记录

时间:2014-10-15 11:38:20

标签: sql sql-server-2008

如果指定了右表列值,如何仅根据右表中的列获取与左连接匹配的记录。

例如

SELECT A.* FROM A LEFT JOIN B ON A.COLUMN_1 = B.COLUMN_1 and B.COLUMN_1 IN (1,2)

-- in above case i want to get only matching records with B.COLUMN_1 is 1 or 2.

如果未指定B.COLUMN_1,我需要从左表中获取所有记录。

2 个答案:

答案 0 :(得分:0)

SELECT 
    A.* 
FROM 
    A 
LEFT JOIN (
    SELECT 
        B.* 
    FROM 
        B 
    WHERE 
        B.COLUMN_1 IN (1,2)
) BB ON A.COLUMN_1 = BB.COLUMN_1

答案 1 :(得分:0)

您可以对这两种表单进行UNION以获取所有数据,例如

SELECT A.* 
FROM A 
LEFT JOIN B 
ON A.COLUMN_1 = B.COLUMN_1 
and B.COLUMN_1 IN (1,2)

UNION

SELECT A.* 
FROM A 
JOIN B ON A.COLUMN_1 = B.COLUMN_1 
and B.COLUMN_1 IN (1,2)