2011-02-14 30 views
0

我有一個SQL選擇,我不知道如何實現這一點。我正在檢查兩個字段,看看這些字段是否在列表中。所以像,兩個字段的條件

Select * from MyTable where col1 or col2 in (select col3 from OtherTable where ID=1) 

我試圖

Select * from MyTable where 
col1 in (select col3 from OtherTable where ID=1) 
or col2 in (select col3 from OtherTable where ID=1) 

但是,這將返回匹配某些原因第一個條件(只返回COL1,但不是COL2)的記錄。

+0

col2和col3具有相同的數據類型? – Silagy 2011-02-14 15:23:23

回答

0

試試這個 -

Select * from MyTable where 
(col1 in (select col3 from OtherTable where ID=1)) 
or 
(col2 in (select col3 from OtherTable where ID=1)) 
0

如果你的子查詢是兩列相同,我會扔到熱膨脹係數,然後做一個左外連接在col1和col2上的熱膨脹係數,然後做你的地方聲明。

;with c3 as 
(
    select col3 
    from OtherTable 
    where ID=1 
) 

select m.* 
from MyTable m 
    left outer join c3 as c1 
     on m.col1=c1.col3 
    left outer join c3 as c2 
     on m.col2=c2.col3 
where 
    (c1.col3>'') 
    or (c2.col3>'') 

如果一個空白的VARCHAR不是null是一個可行的選擇,改變你的where子句爲> =。

0
SELECT t.* 
FROM MyTable t 
    INNER JOIN (
    select col3 
    from OtherTable 
    where ID=1 
) sel ON sel.col3 IN (t.col1, t.col2) 
相關問題