请教一个sql查询的问题
我现在2张表
产品表A:  ID  价格1,价格2,     产品表B:  ID,  价格1,价格2,  user_id
产品表B只含有产品表A的小部分现在我要查询产品表A的所有记录,不过如果产品表B对应user_id含有记录,这把产品表B对应ID的价格覆盖产品表A对应ID的价格
order by 价格1,价格2排序显示(ID , 价格1, 价格2)请问sql语句能不能完成这个功能

解决方案 »

  1.   

    select A.ID,case when user_id is null then  A.价格1 else B.价格1 end as "价格1",
                case when user_id is null then  A.价格2 else B.价格2 end as "价格2"
    from A left outer join B on A.ID=B.ID
    ;
      

  2.   

    select *
    from (select A.ID,case when user_id is null then  A.价格1 else B.价格1 end as "价格1", 
                case when user_id is null then  A.价格2 else B.价格2 end as "价格2" 
          from A left outer join B on A.ID=B.ID ) t
    order by t.价格1,t.价格2
    ;
      

  3.   

    select id, decode(b.user_id,NULL,a.价格1,b.价格1),decode(b.user_id,NULL,a.价格2,b.价格2) from a a, b b where a.id=b.id(+) order by id, decode(b.user_id,NULL,a.价格1,b.价格1),decode(b.user_id,NULL,a.价格2,b.价格2)
      

  4.   

    有人说用union,试了一下
    select id, p1, p2 from a where not exists (select 1 from b where uid = 1 and a.id = b.id)
    union select a.id,p1 ,p2 from a,b where b.uid = 1 and a.id = b.id order by p1, p2;问题就是table b查了2次,好像有点浪费
      

  5.   

    select id,
    nvl(b.p1, a.p1) p1,
    nvl(b.p2, a.p2) p2
    from a left outer join b on a.id=b.id and b.id=1
    order by p1, p2;
      

  6.   

    select A.ID,nvl(  B.价格1 ,A.价格1 ) as 价格1 
     ,nvl( B.价格2 , A.价格2) as "价格2" 
    from A left outer join B on A.ID=B.ID 
    ;
      

  7.   

    多谢各位,其实用case 应该通用点
      

  8.   

    select id, 
    nvl(b.p1, a.p1) p1, 
    nvl(b.p2, a.p2) p2 
    from a left outer join b on a.id=b.id and b.id=1 
    order by p1, p2;这个最好,一个nvl就可以了啊,不用Decode和case when
      

  9.   

    还是比较喜欢decode函数,支持三楼