【发布时间】:2014-07-30 23:01:48
【问题描述】:
以下代码会创建三重记录,但如果我删除事务命令,它会按预期工作,在 in 子句中为每个数字插入一条记录:
insert into table1(id2, col)
select col2, 1
from table2
where col2 in (1, 2, 3) and col2 not in (select id2 from table1 where col = 1)
group by col2;
这是一个 MySQL 错误吗?同一语句不会导致 MSSQL Server 上出现重复记录。
是否可以在不复制记录的情况下运行此查询或类似的查询?
查询前的示例数据:
table1
id | id2 | col
==============
-- empty --
table2
id | col2
==============
1 | 1
2 | 1
3 | 1
4 | 2
5 | 2
6 | 2
7 | 3
8 | 3
9 | 3
查询后的示例数据:
table1 (* duplicated records I don't want)
id | id2 | col
==============
1 | 1 | 1
2 | 1 | 1 *
3 | 1 | 1 *
4 | 2 | 1
5 | 2 | 1 *
6 | 2 | 1 *
7 | 3 | 1
8 | 3 | 1 *
9 | 3 | 1 *
table2 keeps the same
观察:
-
table2有重复值。 - 单独运行选择查询只会返回所需的结果(没有重复)。
- 似乎
insert into() select忽略了distinct和group by子句。
编辑:
我发现出现这个问题是因为 MySQL 忽略了 INSERT INTO ... SELECT 查询上的 GROUP BY 子句。
有没有办法在插入时对这些记录进行分组?
【问题讨论】:
-
必须是您的代码,而不是语句。 MySQL 5.5.32 sqlfiddle.com/#!2/3b29ad/2/0 和 5.6.6 sqlfiddle.com/#!9/3b29a/1/0 都无法重现此问题
标签: mysql group-by insert-select