【问题标题】:How can I retrieve similar rows from different tables in the same query?如何在同一查询中从不同表中检索相似的行?
【发布时间】:2009-05-16 17:58:58
【问题描述】:

假设我有两个或多个填充了用户的表,我想在同一个查询中从这些表中检索所有用户。

表共享一些列,而那些具有相同名称的列是我要检索的列。

类似:

SELECT name, age FROM users1;
SELECT name, age FROM users2;
etc.

注意:这只是一个例子,并不是真正的问题。我无法将这些表合二为一。

【问题讨论】:

    标签: sql mysql


    【解决方案1】:

    你可以使用UNION:

    UNION 用于将多个 SELECT 语句的结果组合成一个结果集。

    第一个 SELECT 语句中的列名用作返回结果的列名。在每个 SELECT 语句的相应位置列出的选定列应具有相同的数据类型。

    一个例子:

    mysql> SELECT 1 as ColumnA,'a' as ColumnB
        -> UNION
        -> SELECT 2, 'b'
        -> UNION
        -> SELECT 3, 'c';
    +---------+---------+
    | ColumnA | ColumnB |
    +---------+---------+
    |       1 | a       |
    |       2 | b       |
    |       3 | c       |
    +---------+---------+
    3 rows in set (0.05 sec)
    

    另请注意:

    UNION 的默认行为是从结果中删除重复的行。可选的 DISTINCT 关键字除了默认值之外没有任何作用,因为它还指定重复行删除。使用可选的 ALL 关键字,不会发生重复行删除,结果包括所有 SELECT 语句中的所有匹配行。

    一个例子:

    mysql> SELECT 1 as x
        -> UNION
        -> SELECT 1;
    +---+
    | x |
    +---+
    | 1 |
    +---+
    1 row in set (0.00 sec)
    
    mysql> SELECT 1 as x
        -> UNION ALL
        -> SELECT 1;
    +---+
    | x |
    +---+
    | 1 |
    | 1 |
    +---+
    2 rows in set (0.00 sec)
    

    【讨论】:

      【解决方案2】:

      您可以使用unionunion all,具体取决于您想要的行为:

      select name, age from users1
      union
      select name, age from users2
      union
      select name, age from users3
      

      或:

      select name, age from users1
      union all
      select name, age from users2
      union all
      select name, age from users3
      

      区别在于union 会删除重复项,而union all 不会。

      如果您知道没有重复项,则应使用union all,这样数据库就不必进行额外的工作来尝试查找重复项。

      【讨论】:

        【解决方案3】:

        试试

        SELECT name, age FROM users1
        UNION
        SELECT name, age FROM users2
        

        【讨论】:

          【解决方案4】:

          还要注意,“union all”会比“union”快得多。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-08-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2015-11-27
            • 2019-11-29
            相关资源
            最近更新 更多