这是正确的吗?
select * from t1
where nvl(t1.a,t1.b) in (select id from t2 where name = 'Apple')a,b是t1中来自t2的Id的列。
我想要在t1.a或t1.b中有“Apple”id的所有行
如果a为null,则id将位于b中。
如果b为null,则id将位于a中。
发布于 2016-06-29 18:12:04
我想要在t1.a或t1.b中有“Apple”id的所有行
不,这不对。
您的查询将得到行,其中t1.a是t2中的id,t1.a是null,t1.b是t2中的id。
你想:
select *
from t1
where EXISTS ( select 1
from t2
where name = 'Apple'
and ( t1.a = t2.id OR t1.b = t2.id ) )或者:
SELECT *
FROM t1
WHERE a IN ( SELECT id FROM t2 WHERE name = 'Apple' )
OR b IN ( SELECT id FROM t2 WHERE name = 'Apple' )或者(如果需要在非匹配值中强制执行NULL ):
select *
from t1
where EXISTS ( select 1
from t2
where name = 'Apple'
and ( ( t1.a = t2.id AND t1.b IS NULL )
OR ( t1.b = t2.id AND t1.a IS NULL ) ) )发布于 2016-06-29 18:16:25
这是对的,但效率很低。我会写
select * from t1
where t1.a in (select id from t2 where name = 'Apple')
union
select * from t1
where t1.b in (select id from t2 where name = 'Apple')发布于 2016-06-29 18:26:06
如果一条记录中的a和b的值为-9999和苹果的ID,则查询将不返回该记录,因为a不是null,而so -9999将与apple id而不是b的值进行比较。
我建议这样做,假设你在t2中只有一张代表“苹果”的记录
select *
from t1
where (select id from t2 where name = 'Apple') in (a, b)如果您可以在t2中有多个名为"Apple“的记录,那么我建议如下:
select distinct t1.*
from t1
inner join t2
on t2.name = 'Apple'
and t2.id in (t1.a, t1.b)https://stackoverflow.com/questions/38106969
复制相似问题