我有一个SQL Select,我不知道如何实现这个目标。我正在检查两个字段以查看是否有任何这些字段在列表中。好吧,
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 :(得分:0)
试试这个 -
Select * from MyTable where
(col1 in (select col3 from OtherTable where ID=1))
or
(col2 in (select col3 from OtherTable where ID=1) )
答案 1 :(得分:0)
如果你的子查询对于两列都是相同的,我会把它扔进一个cte,然后在col1和col2上的cte上做一个左外连接,然后做你的where语句。
;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子句更改为> =。
答案 2 :(得分:0)
SELECT t.*
FROM MyTable t
INNER JOIN (
select col3
from OtherTable
where ID=1
) sel ON sel.col3 IN (t.col1, t.col2)