2011-08-21 27 views
0

我有兩個表: 表1:ID1,字段1,字段2,字段3 表2:ID2,字段1,字段3SQL動態排斥,凝結成一個查詢(SQLite的)

我需要的是:

"select id2 from table2 where field1 = x and field3 = y;" 

,如果返回空,則執行並處理結果:

"select field2 from table1 where field1 = x and field3 = y;" 

有沒有在SQLite的單個查詢執行這個辦法?

回答

1

假設表是可連接於field1field3,那麼這樣的事情應該工作(警告:未經測試):

select 
    case when sum(count_id2)>0 then a.id2 
    else b.field2 end as column 
from(
    select id2,count(1) as count_id2 
    from table2 
    where field1=x and field3=y 
    group by id2 
)a 
join(
    select id2,field2 
    from table1 
    join table2 
    using(field1,field3) 
    where field1=x and field3=y 
)b 
using(id2); 
+0

它不工作,我需要,但我得到的圖片。謝謝。 –

+0

不客氣。 :) – 2011-08-23 07:36:48