我有一个原始表 test1、父子表 test2 和包含搜索值的表 test3。表 test2 在另一列中包含顶级父值。当搜索测试 3 中的任何值时,我们需要选择父值和所有子值。
create table test1 (ID int);
insert into test1 (ID) values (123),(124),(125),(126),(127),(128),(129)
create table test2 (IDC int, IDP int)
insert into test2 (IDC, IDP) values (124,123),(125,123),(127,126),(129,128)
create table test3 (ID int)
insert into test3 (ID) values (123),(127)
select * from test1
where
ID in (select IDC from test2
where IDC in (select ID from test3)
or IDP in (select ID from test3))
or ID in (select IDP from test2
where IDC in (select ID from test3)
or IDP in (select ID from test3))
有没有更好的方式来编写这个查询?
谢谢你,Aleš
最佳答案
所以当表 3 的 ID 与表 2 中的 ID 匹配时,ID 需要存在于表 1 中吗?
这里有一个更简洁的解决方案:
select *
from test1 t1
where exists (
select 1
from test2 t2
join test3 t3 on t3.ID in (t2.IDC, t2.IDP)
where t1.ID in (t2.IDC, t2.IDP)
);
关于sql - 如何正确查询值可以在一列或另一列中的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51478393/