Union
如何將 UNION 與 EXISTS 結合起來?
我有一個看起來像這樣的查詢:
SELECT PubKey, Title FROM Publication UNION SELECT NoteKey, Title, FROM Note
哪個工作正常。當我嘗試向其中添加 EXIST 時,我的麻煩就開始了:
SELECT PubKey, Title FROM Publication UNION SELECT NoteKey, Title, FROM Note WHERE EXISTS (SELECT * FROM UserPublication WHERE UserPublication.PubKey = Publication.PubKey)
這會引發此錯誤:無法綁定多部分標識符“PubKey”。
能不能換一種寫法?
該
WHERE
子句特定於每個人SELECT
,因此您需要將您擁有的那個移動到第一個,SELECT
如下所示:SELECT PubKey, Title FROM Publication WHERE EXISTS ( SELECT * FROM UserPublication WHERE UserPublication.PubKey = Publication.PubKey ) UNION SELECT NoteKey, Title FROM Note
但是,如果要
WHERE
在整個結果集中指定子句。必須這樣做: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 )