Mysql union子句标识表

时间:2012-09-10 13:33:32

标签: mysql select union

我有一个mysql表,它可以在多个表中保存大量数据。所以为了全力以赴,我认为最好的办法是使用一个UNION子句,但是我也想知道结果来自哪个表,因为有些值有多个值而有些值为空。

以下sql似乎不起作用,但我看不出什么错误。

 (SELECT *, `2` AS 'cat' from `2` where `recid` = 'cneta0ld00ah')
  UNION
 (SELECT *, `3` AS 'cat' from `3` where `recid` = 'cneta0ld00ah')
  UNION
 (SELECT *, `4` AS 'cat' from `4` where `recid` = 'cneta0ld00ah')
  UNION
 (SELECT *, `5` AS 'cat' from `5` where `recid` = 'cneta0ld00ah')

所有表格看起来像下面这些名称,1,2,3,4等。

 recid         | item
 -------------------------
 cneta0ld00ah  |   1
 cneta0ld00ab  |   1
 cneta0ld00ad  |   3

我无法更改表的名称,因为它是从我们正在尝试转换并从中提取数据的非常旧的数据库导入的。

如果我在没有'table-name'AS'cat'的情况下运行它,那么它运行正常,一旦我尝试添加表名就会抛出错误说

Unknown column '2' in 'field list'

似乎认为2是列名?

3 个答案:

答案 0 :(得分:3)

问题是围绕'table-name'AS'cat'的反击。反引号用于引用表名和列名,而不是字符串。您应该使用单引号:

 (SELECT *, '2' AS 'cat' from `2` where `recid` = 'cneta0ld00ah')
  UNION
 (SELECT *, '3' AS 'cat' from `3` where `recid` = 'cneta0ld00ah')
  UNION
 (SELECT *, '4' AS 'cat' from `4` where `recid` = 'cneta0ld00ah')
  UNION
 (SELECT *, '5' AS 'cat' from `5` where `recid` = 'cneta0ld00ah')

答案 1 :(得分:0)

所有表格都具有相同的结构吗?在Unionselect *,他们需要。

如果有,请尝试删除括号

SELECT recid, item, `2` AS `cat` from `2` where `recid` = 'cneta0ld00ah'
UNION 
SELECT recid, item, `3` AS `cat` from `3` where `recid` = 'cneta0ld00ah'

答案 2 :(得分:0)

使用UNION ALL代替UNION

(SELECT *, `2` AS 'cat' from `2` where `recid` = 'cneta0ld00ah')
 UNION ALL
(SELECT *, `3` AS 'cat' from `3` where `recid` = 'cneta0ld00ah')
 UNION ALL
(SELECT *, `4` AS 'cat' from `4` where `recid` = 'cneta0ld00ah')
 UNION ALL
(SELECT *, `5` AS 'cat' from `5` where `recid` = 'cneta0ld00ah')
当您选择相关信息时,应使用

UNION,类似于JOIN,因为只会选择不同的值。 UNION ALL不会删除重复项,因此也会减少查找不同值所需的时间。

您还应始终指定列列表,而不是SELECT *