SQL在左连接中使用内部查询

时间:2013-08-26 13:11:46

标签: mysql sql sql-server oracle db2

我有以下两张桌子ONE&两个

ONE           TWO

ID            ID  CODE  
-----         ---------
1             1    1
2             1    2
3             2    1
4             3    1  
5             3    2  
              3    3

需要输出

ID    CODE  
----------  
1     2  
2     1  
3     3  
4     NULL  
5     NULL  

我使用了以下查询,但它抛出错误“与JOIN运算符关联的ON子句或MERGE语句中的ON子句无效。

SELECT  A.ID
       ,B.CODE
FROM   ONE A 
LEFT JOIN
       TWO B
ON     A.ID = B.ID
   AND B.CODE = (
                   SELECT 
                         MAX(Z.CODE)
                   FROM TWO Z
                   WHERE Z.ID = A.ID
            )

3 个答案:

答案 0 :(得分:4)

您可以使用连接和聚合(如果我正确理解逻辑)来执行此操作:

select ONE.id, max(TWO.CODE)
from ONE left outer join
     TWO
     on ONE.id = TWO.id
group by ONE.id;

答案 1 :(得分:2)

由于您还标记了SQL-Server,因此可以使用ROW_NUMBER

WITH CTE AS
(
    SELECT ONE.ID,  TWO.CODE,
        RN = ROW_NUMBER() OVER (PARTITION BY ONE.ID ORDER BY TWO.CODE DESC)
    FROM ONE LEFT OUTER JOIN TWO
        ON ONE.ID=TWO.ID
)
SELECT  ID, CODE FROM CTE WHERE RN = 1

DEMO

答案 2 :(得分:1)

SELECT  A.ID
   ,B.CODE
FROM   ONE A 
LEFT outer JOIN
   (select id,max(code) CODE from two group by id) B
ON     A.ID = B.ID

我相信这就是你要找的......