SQL关键词:Union使用(SQL Keywords: Union usage)

  • Union :将两个或多个查询结果合并,不会有重复数据

    SELECT column_name(s) FROM table_name1
    UNION
    SELECT column_name(s) FROM table_name2
    UNION
    SELECT column_name(s) FROM table_name3

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
UNION
SELECT column_name(s) FROM table_name3
...
  • Union All:将两个或多个查询结果集合并,会有重复数据

    SELECT column_name(s) FROM table_name1
    UNION ALL
    SELECT column_name(s) FROM table_name2
    UNION ALL
    SELECT column_name(s) FROM table_name3

SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
UNION ALL
SELECT column_name(s) FROM table_name3
...
  • 注意:

  UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。

————————
  • Union :将两个或多个查询结果合并,不会有重复数据

    SELECT column_name(s) FROM table_name1
    UNION
    SELECT column_name(s) FROM table_name2
    UNION
    SELECT column_name(s) FROM table_name3

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
UNION
SELECT column_name(s) FROM table_name3
...
  • Union All:将两个或多个查询结果集合并,会有重复数据

    SELECT column_name(s) FROM table_name1
    UNION ALL
    SELECT column_name(s) FROM table_name2
    UNION ALL
    SELECT column_name(s) FROM table_name3

SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
UNION ALL
SELECT column_name(s) FROM table_name3
...
  • be careful:

Select statements within a union must have the same number of columns. Columns must also have similar data types. At the same time, the order of columns in each select statement must be the same.