0

我有一个 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 是一个列名?

4

3 回答 3

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')
于 2012-09-10T13:51:44.833 回答
0

所有的表都具有相同的结构吗?在 a Union, with select *, 他们需要。

如果是这样,请尝试删除括号

SELECT recid, item, `2` AS `cat` from `2` where `recid` = 'cneta0ld00ah'
UNION 
SELECT recid, item, `3` AS `cat` from `3` where `recid` = 'cneta0ld00ah'
于 2012-09-10T13:35:09.277 回答
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 *.

于 2012-09-10T13:49:37.270 回答