使用UNION从多个表中进行选择

时间:2015-05-31 08:19:51

标签: mysql sql

我尝试使用UNION在一个数据库中选择3个表中的记录,但我发现了错误:

  

#1248 - 每个派生表都必须有自己的别名

这是我正在尝试的查询:

SELECT * from
  (SELECT column1, 'table1' from table1
UNION
   SELECT column1, 'table2'  from table2
UNION
   SELECT column1, 'table3'  from table3) 
WHERE column1 not like 'abr%' and length(column1) < 8;

错误是什么意思,我该如何解决并显示正确的结果?

7 个答案:

答案 0 :(得分:4)

SELECT Alis.column1 
  FROM (SELECT column1, 'table1' as which from table1
  UNION ALL
      SELECT column1, 'table2' from table2
  UNION ALL
      SELECT column1, 'table3' from table3
 ) Alis
WHERE column1 not like 'abr%' and length(column1) < 8;

答案 1 :(得分:3)

您必须在内部选择或派生表中为您的列添加别名,也为自己添加别名,如下所示:

SELECT * 
FROM
    (SELECT column1, 'table1' as t from table1
     UNION ALL
     SELECT column1, 'table2' as t from table2
     UNION ALL
     SELECT column1, 'table3' as t from table3
    ) As dt
WHERE 
    column1 NOT LIKE 'abr%' 
  AND 
    length(column1) < 8;

已编辑:
我将UNION更改为UNION ALL作为效果问题,并且不会有任何重复;)。

答案 2 :(得分:2)

您需要为派生表提供一个别名,如:

SELECT * from
  (SELECT column1, 'table1' from table1
UNION
   SELECT column1, 'table2'  from table2
UNION
   SELECT column1, 'table3'  from table3) dtAlias
WHERE column1 not like 'abr%' and length(column1) < 8;

答案 3 :(得分:2)

正如其他人所说,问题很简单 - 在最后一个括号后需要一个表别名。您还需要第二列的列别名。

出于性能原因,更重要的是您应该使用UNION ALLUNION会产生删除重复项的开销,在这种情况下完全没有必要:

SELECT t.* 
FROM (SELECT column1, 'table1' as which from table1
      UNION ALL
      SELECT column1, 'table2' from table2
      UNION ALL
      SELECT column1, 'table3' from table3
     ) t
WHERE column1 not like 'abr%' and length(column1) < 8;

对于MySQL中的性能,我认为您希望将WHERE子句移动到子查询,并且在所有三个表中的column1上创建索引:

SELECT t.* 
FROM (SELECT column1, 'table1' as which from table1 WHERE column1 not like 'abr%' and length(column1) < 8
      UNION ALL
      SELECT column1, 'table2' from table2 WHERE column1 not like 'abr%' and length(column1) < 8
      UNION ALL
      SELECT column1, 'table3' from table3 WHERE column1 not like 'abr%' and length(column1) < 8
     ) t

答案 4 :(得分:1)

你应该为派生表命名,如下所示

SELECT * from
  (SELECT column1, 'table1' from table1
UNION
   SELECT column1, 'table2'  from table2
UNION
   SELECT column1, 'table3'  from table3) as new_table
WHERE column1 not like 'abr%' and length(column1) < 8;

答案 5 :(得分:1)

错误非常自我解释,您只需要使用嵌套选择和联合命名您创建的派生表。 添加别名来修复我们的错误应该足够了,如下所示:

  SELECT * from
  (SELECT column1, 'table1' from table1
   UNION
   SELECT column1, 'table2'  from table2
   UNION
   SELECT column1, 'table3'  from table3) as youralias 
   WHERE column1 not like 'abr%' and length(column1) < 8;

答案 6 :(得分:1)

您应该在子查询中使用的表中添加别名。这是正确的版本:

USE test2;

SELECT * from
  (SELECT column1, 'table1' from table1 as t1
UNION
   SELECT column1, 'table2'  from table2 as t2
UNION
   SELECT column1, 'table3'  from table3) as t3
WHERE column1 not like 'abr%' and length(column1) < 8;