範例 UNION 查詢 - Amazon Redshift

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

範例 UNION 查詢

在下列 UNION 查詢中,SALES 資料表中的資料列會與 LISTING 資料表中的資料列合併。會從每個資料表選取三個相容的資料欄;在此情況下,對應的資料欄會有相同的名稱和資料類型。

最終結果集是依 LISTING 資料表中的第一欄排序,且限於擁有最高 LISTID 值的 5 個資料列。

select listid, sellerid, eventid from listing union select listid, sellerid, eventid from sales order by listid, sellerid, eventid desc limit 5; listid | sellerid | eventid --------+----------+--------- 1 | 36861 | 7872 2 | 16002 | 4806 3 | 21461 | 4256 4 | 8117 | 4337 5 | 1616 | 8647 (5 rows)

以下範例說明如何將常值新增至 UNION 查詢的輸出,以便查看結果集中的每個資料列是由哪個查詢表達式所產生。查詢會將來自第一個查詢表達式的資料列識別為 "B" (表示買方),來自第二個查詢表達式的資料列識別為 "S" (表示賣家)。

查詢會識別價值 10,000 USD 以上的票券交易買方和賣家。UNION 運算子任一邊的兩個查詢表達式之間唯一的差異,就是 SALES 資料表的聯結資料欄。

select listid, lastname, firstname, username, pricepaid as price, 'S' as buyorsell from sales, users where sales.sellerid=users.userid and pricepaid >=10000 union select listid, lastname, firstname, username, pricepaid, 'B' as buyorsell from sales, users where sales.buyerid=users.userid and pricepaid >=10000 order by 1, 2, 3, 4, 5; listid | lastname | firstname | username | price | buyorsell --------+----------+-----------+----------+-----------+----------- 209658 | Lamb | Colette | VOR15LYI | 10000.00 | B 209658 | West | Kato | ELU81XAA | 10000.00 | S 212395 | Greer | Harlan | GXO71KOC | 12624.00 | S 212395 | Perry | Cora | YWR73YNZ | 12624.00 | B 215156 | Banks | Patrick | ZNQ69CLT | 10000.00 | S 215156 | Hayden | Malachi | BBG56AKU | 10000.00 | B (6 rows)

以下範例使用 UNION ALL 運算子,因為重複的資料列 (若找到) 需保留在結果中。若是特定活動 ID 系列,查詢會針對與各個活動相關聯的每筆銷售傳回 0 或更多資料列,並針對該活動的每份清單傳回 0 或 1。LISTING 和 EVENT 資料表中每個資料列的活動 ID 都是唯一的,但 SALES 資料表中相同的活動和清單 ID 組合可能會有多筆銷售。

結果集中的第三個資料欄會識別資料列的來源。若是來自 SALES 資料表,則會在 SALESROW 資料欄中標示為「Yes (是)」 (SALESROW 是 SALES.LISTID 的別名)。若資料列來自 LISTING 資料表,則會在 SALESROW 資料欄中標示為「No (否)」。

在此情況下,結果集會包含活動 7787、清單 500 的三個銷售資料列。換句話說,此清單與活動組合發生了三筆不同的交易。另外兩份清單 501 和 502 並未產生任何銷售,因此查詢針對這些清單 ID 產生的唯一資料列是來自 LISTING 資料表 (SALESROW = 'No')。

select eventid, listid, 'Yes' as salesrow from sales where listid in(500,501,502) union all select eventid, listid, 'No' from listing where listid in(500,501,502) order by listid asc; eventid | listid | salesrow ---------+--------+---------- 7787 | 500 | No 7787 | 500 | Yes 7787 | 500 | Yes 7787 | 500 | Yes 6473 | 501 | No 5108 | 502 | No (6 rows)

若您執行相同查詢,但未使用 ALL 關鍵字,結果只會保留其中一項銷售交易。

select eventid, listid, 'Yes' as salesrow from sales where listid in(500,501,502) union select eventid, listid, 'No' from listing where listid in(500,501,502) order by listid asc; eventid | listid | salesrow ---------+--------+---------- 7787 | 500 | No 7787 | 500 | Yes 6473 | 501 | No 5108 | 502 | No (4 rows)