2017-03-16 106 views
0

我有2個查詢與不同的邏輯,我試圖找出兩者之間的區別。SQL查詢2個查詢之間的差異

例如:

  • 查詢1:選擇所有元音字母的名字,總:10
  • 查詢2:選擇以元音結尾的所有名字,共:2

如何我會去查找2個查詢之間的剩餘8個值嗎?我曾嘗試做以下,但仍沒有運氣:

Q1 except Q2 
UNION 
Q2 except Q1 

回答

3
(Query for Selecting all the names with vowels) 

EXCEPT 

(Query for Selecting all the names ending in vowels) 
+0

只是Q1除了Q2,並且確保Q1返回Q2以上 – LONG

1

另一種選擇是寫與所需where條款查詢。

select * 
from t 
where name like '%[aeiou]%' 
    and name not like '%[aeiou]' 

使用兩個common table expressionsnot exists()另一種選擇:

with q1 as (
/* query 1 */ 
) 
, q2 as (
/* query 2 */ 
) 
select * 
from q1 
where not exists (
    select 1 
    from q2 
    where q1.name = q2.name 
) 
0

按照你的描述,查詢1的結果必須包含QUERY2的reuslt。 所以,你可以使用

Q1 EXCEPT Q2 

或者Q1,其中NOT EXISTS Q2

0

,除非你正在查詢對大型數據將是昂貴的。所以你可以去LEFT OUTER JOIN

select * from Q1 left outer join Q2 on Q1.ID=Q2.ID where Q2.ID IS NULL