sql查询问题

请问各位,我现在有两个表A, R, B三个表,希望三个表join,给定一个数x,希望同时满足下面3个条件,

  1. A.id与R的aid对应,且B.id对应R.bid
  2. 若R中不存在与A对应的数据时,即没有数据满足R.aid=A.id时,R对应的数据为空,同时链接之后B的数据也为空。
  3. 若R存在与A对应的数据,此时连接B表,(这里假设肯定存在B与R对应的数据),当B的b字段不为给定的数x,即B.b!=x,连接之后R与B对应的列为空,当B.b=x,则查询出对应的结果。

似乎用左链接可以满足1,2但是不能满足3,使用inner join满足不了2,3,最差的情况视乎是查询两次?

阅读 2.6k
4 个回答

select * from A left join R on R.aid=A.id left join B on B.rid=r.id and x=1
不是很懂为什么说用left join不行

select R.* from R, A, B where R.aid=A.id AND R.bid=B.id AND B.b != x

select
  a.id as a_id,
  case
    when R.aid is null then ''
    when R.aid is not null and B.b = x then R.aid
    when R.aid is not null and B.b != x then ''
  end as r_aid,
  case
    when R.aid is null then ''
    when R.aid is not null and B.b = x then B.id
    when R.aid is not null and B.b != x then ''
  end as b_id
  from A,R,B
where A.id=R.aid(+)
and R.aid=B.id;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题