我有一个原始表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))
是否有更好的方法编写此查询?
谢谢你,阿莱什
答案 0 :(得分:2)
您可以尝试以下方法:
select * from test1 t1
where exists(select 1 from test2 t2
where (t1.ID = t2.IDC or t1.ID = IDP)
and exists(select 1 from test3
where t2.IDC = ID or t2.IDP = ID))
答案 1 :(得分:2)
因此,当table3 ID与table2中的ID匹配时,该ID是否需要存在于table1中?
这是一个更简洁的解决方案:
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)
);
答案 2 :(得分:1)
这是另一种方法
SELECT * FROM #test1
WHERE ID IN (
SELECT VAL.X FROM #test2 T2
INNER JOIN #test3 T3 ON T2.IDC = T3.ID OR T2.IDP = T3.ID
CROSS APPLY(VALUES (IDC),(IDP),(ID)) VAL(X)
)
结果:
ID
-----
123
124
125
126
127