【问题标题】:Triplicated records on insert with select使用选择插入三重记录
【发布时间】: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 group-by insert-select


【解决方案1】:

我发现出现这个问题是因为 MySQL 忽略了 INSERT INTO ... SELECT 查询上的 GROUP BY 子句。

不知道具体原因,但如果我使用不使用 GROUP BY 或 DISTICT 的查询,它可以工作。

【讨论】:

    猜你喜欢
    • 2010-11-15
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-16
    • 1970-01-01
    • 2015-03-29
    • 2021-11-26
    • 2013-08-17
    相关资源
    最近更新 更多