insert多条 - mysql insert overwrite



在INSERT MySQL中不能使用UNION? (1)

我有一个选择查询,工作正常。 但是,当我把它包装到一个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

我的猜测是你错过了个别选择上的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




union