使用连接从左表中获取所有数据

时间:2013-06-14 17:12:18

标签: sql-server sql-server-2008

我有两张桌子,如下所示。

Id Name                            Id   Status
--------                           -------------------
1   A                              1        Approved
2   B                              6        Approved
3   C                              4        Pending
4   D                              1        Approved
5   E                              1        Pending
6   F                              3        Pending
                                   5        Rejected

现在这就是我想要输出的方式:

Id  Name  Status
-------------------
1    A    Pending
2    B    
3    C    Pending 
4    D    Pending
5    E
6    F

我尝试过使用左连接,但我得到了多行。

select t1.ID,Name,Status from t1 left join t2 on t1.id=t2.id

如果我添加Status = pending,我只得到ID 1和3。     以下是我尝试的查询:

select distinct t1.id,name,status from t1 left join t2 on t1.id=t2.id  (this gives me duplicate records i.e id 1 is occurs twice with approved and pending)

以及

select distinct t1.id,name,status from t1 left join t2 on t1.id=t2.id where t2.status='pending'  (gives me only 1,3 and 4)

任何人都可以帮助我 提前谢谢。

1 个答案:

答案 0 :(得分:5)

要包含T1中的所有行,只有来自T2 status = 'pending'的所有行将条件移至ON子句SQL Fiddle

SELECT t1.ID,
       Name,
       Status
FROM   t1
       LEFT JOIN t2
         ON t1.id = t2.id
            AND t2.status = 'pending' 

如果您可以执行欺骗,则每id只返回一行(Fiddle

WITH CTE AS
(
SELECT DISTINCT id, Status
FROM T2
WHERE Status = 'Approved' 
)
SELECT t1.ID,
       Name,
       Status
FROM   t1
       LEFT JOIN CTE
         ON t1.id = CTE.id