问题是:
    有a, b 两个表, 分别有id1 和 id2 关键字段互相关联,关联条件是 
     b 表中要找出与a 表相同id1, 并且 id2 <= a.id2 中最大的一条相关联.    另:此语法在 sql 中正常, 在 oracle 中报错:"列不能外部连接到子查询".    求在oracle 中的写法!!!    请高手出招, mail: [email protected]    SELECT a.*, b.*  FROM a LEFT JOIN b ON a.id1=b.id1 AND b.id2=(select max(id2) from b where id1=a.id1 and id2<=a.id2) WHERE (some condition)

解决方案 »

  1.   

    select * from a,b where a.id1=b.id2 and b.id2=(select max(id2) from b where b.id1=a.id1 and b.id2 <=a.id2 group by group by b.id1 )
    and (some condition)
      

  2.   

    select * from a,b where a.id1=b.id1 and b.id2 in (select max(a.id2) from b where b.id1=a.id1 and b.id2  <=a.id2 group by group by b.id1 ) 
    and (some condition)
      

  3.   

    感谢 richard 但 from a,b 则成了 inner join 了,没能体现a表的记录数量, 特别是当a 表的某条记录在b中无对应时就会少出一条记录
      

  4.   

    select * from a,b where a.id1=b.id1 and b.id2 in (select max(a.id2) from b where b.id1=a.id1 and b.id2   <=a.id2 group by group by b.id1 )  
    and (some condition)union
    select * from a,b where a.id1=b.id1(+) where b.id1 is null
      

  5.   

    select aa.*
    from(
         select a.*,b.*,
                row_number() over (partition by a.id1 order by b.id2 desc) rn
           from a,b
          where a.id1=b.id1(+)
          and b.id2<=a.id2)  aa
    where aa.rn=1
      

  6.   

    再次感谢 richard      但是这种写法在阅读性上欠佳,特别是与在sql 中的那句相比    另外我的情况是从 a 表出发, 同样情况要连接 b 表, c, d, ....(数量不能确定),如:    SELECT a.*, b.*  FROM a LEFT JOIN b ON a.id1=b.id1 AND b.id2=(select max(id2) from b where id1=a.id1 and id2 <=a.id2)LEFT JOIN c ON a.id1=c.id1 AND c.id2=(select max(id2) from c where id1=a.id1 and id2 <=a.id2)LEFT JOIN d ON a.id1=d.id1 AND d.id2=(select max(id2) from d where id1=a.id1 and id2 <=a.id2)(...) WHERE (条件包含 a,b,c,d 中的字段)
      

  7.   


    表比较多,每张表中的记录也比较多的话,建议不要用sql语句实现;
    用存储过程吧
      

  8.   

    非常感谢各位的参与!!!
    SELECT a.*, b.*,(or other)  FROM a    LEFT JOIN b ON a.id1=b.id1 AND b.id2=(select max(id2) from b where id1=a.id1 and id2  <=a.id2)    LEFT JOIN c ON a.id1=c.id1 AND c.id2=(select max(id2) from c where id1=a.id1 and id2  <=a.id2)    LEFT JOIN d ON a.id1=d.id1 AND d.id2=(select max(id2) from d where id1=a.id1 and id2  <=a.id2)(...)    WHERE (条件包含 a,b,c,d 中的字段)以上是我在 sql 中成功运行了的, 感觉可阅读性较好, 求在 oracle 中的写法, 非赏感谢!!!
      

  9.   

    我觉得left join的可阅读性没(+)的好