鍍金池/ 問(wèn)答/數(shù)據(jù)庫(kù)  HTML/ sql查詢(xún)問(wèn)題

sql查詢(xún)問(wèn)題

請(qǐng)問(wèn)各位,我現(xiàn)在有兩個(gè)表A, R, B三個(gè)表,希望三個(gè)表join,給定一個(gè)數(shù)x,希望同時(shí)滿足下面3個(gè)條件,

  1. A.id與R的aid對(duì)應(yīng),且B.id對(duì)應(yīng)R.bid
  2. 若R中不存在與A對(duì)應(yīng)的數(shù)據(jù)時(shí),即沒(méi)有數(shù)據(jù)滿足R.aid=A.id時(shí),R對(duì)應(yīng)的數(shù)據(jù)為空,同時(shí)鏈接之后B的數(shù)據(jù)也為空。
  3. 若R存在與A對(duì)應(yīng)的數(shù)據(jù),此時(shí)連接B表,(這里假設(shè)肯定存在B與R對(duì)應(yīng)的數(shù)據(jù)),當(dāng)B的b字段不為給定的數(shù)x,即B.b!=x,連接之后R與B對(duì)應(yīng)的列為空,當(dāng)B.b=x,則查詢(xún)出對(duì)應(yīng)的結(jié)果。

似乎用左鏈接可以滿足1,2但是不能滿足3,使用inner join滿足不了2,3,最差的情況視乎是查詢(xún)兩次?

回答
編輯回答
敢試

select * from A left join R on R.aid=A.id left join B on B.rid=r.id and x=1
不是很懂為什么說(shuō)用left join不行

2017年6月21日 03:22
編輯回答
艷骨

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

2017年9月28日 09:16
編輯回答
笑忘初
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;
2018年9月8日 04:02
編輯回答
浪婳
select * from R, A, B where R.aid=A.id AND R.bid=B.id AND B.b != x

或者你可以依次進(jìn)行查詢(xún)吧

2018年8月4日 13:02