Sql - Multiple Layers Of Correlated Subqueries
Solution 1:
Try this:
select * from (
select a.*, b.id as b_id, c.id as c_id
from table_A as a
left outer join table_B as b on a.id = b.id
left outer join table_C as c on c.id = a.id
) T
where b_id isnulland c_id isnull
Another implementation is this:
select a1.*
from table_A as a1
inner join (
select a.idfrom table_A
except
select b.idfrom table_B
except
select c.idfrom table_c
) as a2 on a1.id = a2.id
Note the restrictions on the form of the sub-query as described here. The second implementation, by most succinctly and clearly describing the desired operation to SQL Server, is likely to be the most efficient.
Solution 2:
You have two WHERE
clauses in (the external part of) your second query. That is not valid SQL. If you remove it, it should work as expected:
select * from table_A as a
wherenotexists (select1from table_B as b
where a.id = b.id)
AND
notexists (select1from table_C as c -- WHERE removed
where a.id = c.id) ;
Tested in SQL-Fiddle (thnx @Alexander)
Solution 3:
how about using LEFT JOIN
SELECT a.*FROM TableA a
LEFTJOIN TableB b
ON a.ID = b.ID
LEFTJOIN TableC c
ON a.ID = c.ID
WHERE b.ID ISNULLAND
c.ID ISNULL
Solution 4:
One more option with NOT EXISTS operator
SELECT*FROM dbo.test71 a
WHERENOTEXISTS(
SELECT1FROM (SELECT b.ID
FROM dbo.test72 b
UNIONALLSELECT c.ID
FROM dbo.test73 c) x
WHERE a.ID = x.ID
)
Demo on SQLFiddle
Option from @ypercube.Thank for the present;)
SELECT*FROM dbo.test71 a
WHERENOTEXISTS(
SELECT1FROM dbo.test72 b
WHERE a.ID = b.ID
UNIONALLSELECT1FROM dbo.test73 c
WHERE a.ID = c.ID
);
Demo on SQLFiddle
Solution 5:
I do not like "not exists" but if for some reason it seems to be more logical to you; then you can use a alias for your first query. Subsequently, you can re apply another "not exists" clause. Something like:
SELECT * FROM
( select * from tableA as a
wherenot exists (select1from tableB as b
where a.id = b.id) )
AS A_NOT_IN_B
WHERENOT EXISTS (
SELECT1FROM tableC as c
WHERE c.id = A_NOT_IN_B.id
)
Post a Comment for "Sql - Multiple Layers Of Correlated Subqueries"