patternMinor
Howto combine UNION with EXISTS?
Viewed 0 times
howtocombinewithunionexists
Problem
I have a query that looks like this:
Which works fine. My trouble start when I try to add an EXIST to it:
That throws this error: The multi-part identifier "PubKey" could not be bound.
Could it be written another way?
SELECT PubKey, Title FROM Publication
UNION
SELECT NoteKey, Title, FROM NoteWhich works fine. My trouble start when I try to add an EXIST to it:
SELECT PubKey, Title FROM Publication
UNION
SELECT NoteKey, Title, FROM Note
WHERE EXISTS (SELECT * FROM UserPublication WHERE UserPublication.PubKey = Publication.PubKey)That throws this error: The multi-part identifier "PubKey" could not be bound.
Could it be written another way?
Solution
The
However, if you want to specify the
WHERE clause is specific to each individual SELECT so you would need to move the one you have to the first SELECT like this:SELECT PubKey, Title FROM Publication
WHERE EXISTS (
SELECT *
FROM UserPublication
WHERE UserPublication.PubKey = Publication.PubKey
)
UNION
SELECT NoteKey, Title FROM NoteHowever, if you want to specify the
WHERE clause across the entire result set. This must be done like so:SELECT * FROM (
SELECT PubKey, Title FROM Publication
UNION
SELECT NoteKey, Title FROM Note
) AS A
WHERE EXISTS (
SELECT *
FROM UserPublication
WHERE UserPublication.PubKey = A.PubKey
)Code Snippets
SELECT PubKey, Title FROM Publication
WHERE EXISTS (
SELECT *
FROM UserPublication
WHERE UserPublication.PubKey = Publication.PubKey
)
UNION
SELECT NoteKey, Title FROM NoteSELECT * FROM (
SELECT PubKey, Title FROM Publication
UNION
SELECT NoteKey, Title FROM Note
) AS A
WHERE EXISTS (
SELECT *
FROM UserPublication
WHERE UserPublication.PubKey = A.PubKey
)Context
StackExchange Database Administrators Q#127970, answer score: 5
Revisions (0)
No revisions yet.