Select

合併兩個選擇然後排序並刪除重複項

  • October 22, 2016

我有兩個選擇語句。是否可以將兩個結果合併在一起並從最終合併結果列表中刪除重複項(而不是單獨處理查詢)。

查詢 1

SELECT DISTINCT
   UM.UMKEY,
   OS.MAILTITLE,
   UM.ADDRESS01,
   UM.ADDRESS02,
   UM.ADDRESS03
FROM (OS LEFT JOIN UM ON OS.HOMEKEY = UM.UMKEY) 
LEFT JOIN UM AS MUM ON OS.MAILKEY = MUM.UMKEY
WHERE 
   (OS.OS_EMAIL != '') 
   AND (UM.INTERNATIONAL != 'Y') 
   AND (OS.DECEASED != 'Y') 
   AND (OS.GENDER  = 'F') 
   AND (OS.MAIL_LIST = 'Y')
ORDER BY UM.UMKEY ASC

查詢 2

SELECT DISTINCT
   UM.UMKEY,
   DF.MAILTITLE,
   UM.ADDRESS01,
   UM.ADDRESS02,
   UM.ADDRESS03
FROM ST INNER JOIN DF ON (ST.FAMILY = DF.DFKEY) 
INNER JOIN UM ON DF.HOMEKEY = UM.UMKEY
WHERE 
   ST.STATUS = 'FULL'
UNION
SELECT DISTINCT
   UM.UMKEY,
   DF.MAILTITLE,
   UM.ADDRESS01,
   UM.ADDRESS02,
   UM.ADDRESS03
FROM ST INNER JOIN DF ON (ST.FAMB = DF.DFKEY) 
INNER JOIN UM ON DF.HOMEKEY = UM.UMKEY
WHERE ST.STATUS = 'FULL'
ORDER BY UM.UMKEY ASC

在兩個查詢之間使用聯合。UNION 命令用於從兩個表中選擇相關資訊,很像 JOIN 命令。但是,當使用 UNION 命令時,所有選定的列都需要具有相同的數據類型。使用 UNION,只選擇不同的值。它還將提供更好的性能,因為您不需要對兩個查詢都進行選擇區域,但它會得到不同的結果。

SELECT
UM.UMKEY,
OS.MAILTITLE,
UM.ADDRESS01,
UM.ADDRESS02,
UM.ADDRESS03
FROM (OS LEFT JOIN UM ON OS.HOMEKEY = UM.UMKEY) Left Join UM as MUM On OS.MAILKEY = MUM.UMKEY
WHERE (OS.OS_EMAIL != '') And (UM.INTERNATIONAL != 'Y') And (OS.DECEASED != 'Y') And (OS.GENDER  = 'F') And (OS.MAIL_LIST = 'Y')
UNION
SELECT 
UM.UMKEY,
DF.MAILTITLE,
UM.ADDRESS01,
UM.ADDRESS02,
UM.ADDRESS03
FROM ST INNER JOIN DF ON (ST.FAMILY = DF.DFKEY) INNER JOIN UM ON DF.HOMEKEY = UM.UMKEY
WHERE ST.STATUS = 'FULL'
UNION
SELECT 
UM.UMKEY,
DF.MAILTITLE,
UM.ADDRESS01,
UM.ADDRESS02,
UM.ADDRESS03
FROM ST INNER JOIN DF ON (ST.FAMB = DF.DFKEY) INNER JOIN UM ON DF.HOMEKEY = UM.UMKEY
WHERE ST.STATUS = 'FULL'
ORDER BY UM.UMKEY ASC

引用自:https://dba.stackexchange.com/questions/152545