本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
示例 UNION 查询
在以下 UNION 查询中,SALES 表中的行将与 LISTING 表中的行合并。从每个表中选择三个兼容的列;在这种情况下,对应的列具有相同的名称和数据类型。
select listid, sellerid, eventid from listing union select listid, sellerid, eventid from sales listid | sellerid | eventid --------+----------+--------- 1 | 36861 | 7872 2 | 16002 | 4806 3 | 21461 | 4256 4 | 8117 | 4337 5 | 1616 | 8647
以下示例说明如何将文本值添加到 UNION 查询的输出,以便您查看哪个查询表达式生成了结果集中的每一行。查询将第一个查询表达式中的行标识为“B”(针对买家),并将第二个查询表达式中的行标识为“S”(针对卖家)。
查询标识门票事务费用等于或大于 $10000 的买家和卖家。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 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
以下示例使用 UNION ALL 运算符,因为需要在结果中保留重复行(如果发现重复行)。对于特定系列的活动 IDs,该查询会为与每个事件关联的每笔销售返回 0 行或更多行,为该事件的每个列表返回 0 或 1 行。LISTING 和 EVENT 表中的每一行 IDs 都有唯一的事件,但是销售表 IDs 中相同的事件和列表组合可能会有多笔销售。
结果集中的第三个列标识行的来源。如果行来自 SALES 表,则在 SALESROW 列中将其标记为“Yes”。(SALESROW 是 SALES.LISTID 的别名。) 如果行来自 LISTING 表,则在 SALESROW 列中将其标记为“No”。
在本示例中,结果集包含针对列表 500,活动 7787 的三个销售行。换而言之,将针对此列表和活动组合执行三个不同的事务。另外两个清单(501 和 502)没有产生任何销售额,因此查询为这些列表生成的唯一一行 IDs 来自清单表(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) eventid | listid | salesrow ---------+--------+---------- 7787 | 500 | No 7787 | 500 | Yes 7787 | 500 | Yes 7787 | 500 | Yes 6473 | 501 | No 5108 | 502 | No
如果运行不带 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) eventid | listid | salesrow ---------+--------+---------- 7787 | 500 | No 7787 | 500 | Yes 6473 | 501 | No 5108 | 502 | No