【问题标题】:Primary key without duplicated values没有重复值的主键
【发布时间】:2017-07-13 19:12:26
【问题描述】:

我正在尝试并成功在 Redshif 中创建主键

   create table my_table(id int ,
    primary key(id));


insert into my_table values
(id),
(1),
(1),
(20);

select count(*) from my_table

3

但它允许我上传重复值,

据我所知主键应该包含唯一值,

我做错了吗?

【问题讨论】:

  • 你能展示一个完整的sn-p作品吗(尽管它应该会失败)?主键确实应该禁止重复值。

标签: sql amazon-redshift


【解决方案1】:

你可以在这里找到答案

How to create an Index in Amazon Redshift

其中一个答案提到了您的主键问题

【讨论】:

    【解决方案2】:

    创建一个identity key,它将作为一个 auto_increment 代理键。这将同时达到目的 - 唯一标识表中的记录并防止插入重复值。

    让我们创建一个虚拟表:

    create table scratchpad.test_1
    (id bigint identity(1,1),
    name varchar(10));
    
    insert into scratchpad.test_1(name)
    values
    ('a'),('b'),('c'),('d');
    
    select * from scratchpad.test_1;
    

    id 列充当primary key。从表中删除任何记录不会影响其他值的排序,并且 id 列可用于唯一标识后续行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 2016-08-08
      • 2017-03-14
      • 2013-01-06
      相关资源
      最近更新 更多