3

我有一个工作正常的选择查询。但是当我将它包装到一个 INSERT 语句中时,我得到了一个错误。

错误 1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 3 行的 '(SELECT DISTINCT NULL AS id,NULL AS core_value_id,NULL AS translation_id'附近使用正确的语法

我可以通过为每个源表使用 1 个插入来解决这个问题。但是有没有办法用一个查询来做到这一点?为什么这不起作用?

这是查询。

INSERT INTO `some_table`
(
(SELECT DISTINCT
NULL AS `id`,
NULL AS `core_value_id`,
NULL AS `translation_id`,
t1.`upc` AS `source_value`,
t1.`upc` AS `value`,
COUNT(*) AS `count`
FROM  `source_table_1` t1
GROUP BY `upc`)

UNION ALL
(SELECT DISTINCT
NULL,NULL,NULL,
t1.`upc`,
t1.`upc`,
COUNT(*) AS `count`
FROM  `source_table_2` t1
GROUP BY `upc`
)
ORDER BY `count` DESC
)

这是表定义:

CREATE TABLE `some_table` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `core_value_id` int(11) DEFAULT NULL,
 `translation_id` int(11) DEFAULT NULL,
 `source_value` varchar(255) NOT NULL,
 `value` varchar(255) DEFAULT NULL,
 `count` int(11) NOT NULL,
 PRIMARY KEY (`id`),
 KEY `core_value_id` (`core_value_id`),
 KEY `translation_id` (`translation_id`),
 KEY `source_value` (`source_value`),
 KEY `value` (`value`),
 KEY `count` (`count`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

source_tables 看起来像这样:

CREATE TABLE `source_table_1` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `upc` bigint(20) DEFAULT NULL,
 PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8

upc 列的数据如下:

123456789012
123456789013
123456789014
123456789015
123456789016
123456789017
4

1 回答 1

5

我的猜测是您SELECT在单个选择之上缺少一个子句。此外,括号也不合适。试试这个:

INSERT INTO `some_table`
SELECT      * 
FROM 
            (
             SELECT   DISTINCT NULL AS `id`, NULL AS `core_value_id`,
                      NULL AS `translation_id`, t1.`upc` AS `source_value`,
                      t1.`upc` AS `value`, COUNT(*) AS `count`
             FROM     `source_table_1` t1
             GROUP BY `upc`

             UNION ALL

             SELECT   DISTINCT NULL, NULL, NULL, t1.`upc`, t1.`upc`, 
                      COUNT(*) AS `count`
             FROM     `source_table_2` t1
             GROUP BY `upc`
            ) AS dt
ORDER BY    `count` DESC
于 2012-10-31T06:39:24.327 回答