4

我有两个表,如下所示。

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

如果我添加 where Status=pending 我只会得到 ids 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)

任何人都可以帮助我,在此先感谢。

4

1 回答 1

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万一出现欺骗行为,您只能返回一行(小提琴

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
于 2013-06-14T17:14:13.927 回答