gpt4 book ai didi

mysql - 在现有表sql上创建主键

转载 作者:行者123 更新时间:2023-11-29 02:26:51 26 4
gpt4 key购买 nike

我有一个如下形式的表格:

   create table tab1(i1 int, i2 character varying);

我想将 i1 作为主键。但是我的问题是 i1 列包含重复的行。为了实现这一点,我创建了以下形式的表格:

   create table tab2(i1 int, i2 character varying);
insert into tab2 (i1, i2)
(select distinct * from tab1);
alter table tab2 add primary key(i1);

这样做之后我得到以下错误:

NOTICE:  ALTER TABLE / ADD PRIMARY KEY will create implicit index "tab2_pkey" for table "tab2"
ERROR: could not create unique index "tab2_pkey"
DETAIL: Key (i1)=(1958) is duplicated.

有人可以帮我在 tab2 上创建主键吗?

最佳答案

Key (i1)=(1958) is duplicated.

请运行选择

select distinct * from tab1 where i1 = 1958

并确保在结果中返回多行。例如,行

 | i1   |  i2 | 
| 1958 | '1' |
| 1958 | '2' |

不同且不同,返回 2 行。如果你真的需要 i1 上的主键,你必须提供唯一值被插入。试试这个:

insert into tab2 (i1, i2) (select i1, max(i2) from tab1 group by i1);

您可以使用任何聚合来代替函数 max()。

关于mysql - 在现有表sql上创建主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20172772/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com