以下代码创建了三重记录,但如果我删除事务命令,它会按预期工作,只为in
子句中的每个数字插入 1 条记录:
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 忽略了查询中的GROUP BY
子句。INSERT INTO ... SELECT
有没有办法在插入时对这些记录进行分组?