gpt4 book ai didi

sql - postgres 在冲突错误时插入 - 没有唯一或排除约束

转载 作者:行者123 更新时间:2023-12-04 12:17:45 25 4
gpt4 key购买 nike

我在 postgres 中有两个表 daily_reportsummary_songs .

用于创建表的 Sql 文件在这里:https://nofile.io/f/Ef94rMFRh6C/file.sql

我要更新summary_songs在每天结束时,条件如下:

  • 如果userid已经不存在,则从daily_report记录需要插入summary_songs
  • 如果userid存在,则 summary_songs.countid = summary_songs.countid+ daily_report.countid .

  • 我使用以下查询来更新 summary_songs :
    insert into summary_songs 
    (select * from daily_report as B)
    on conflict (userid, songd)
    do update set countid = countid+excluded.countid ;

    我得到以下错误:

    ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification

    最佳答案

    使用 on conflict您需要强制执行 unique(userid, songd)在您的 summary_songs table :

    SQL Fiddle

    PostgreSQL 9.6 架构设置 :

    CREATE TABLE summary_songs (
    date_time date NOT NULL,
    userid integer NOT NULL,
    songd integer NOT NULL,
    countid integer NOT NULL,
    unique(userid, songd)
    );


    CREATE TABLE daily_report(
    date_time date NOT NULL,
    userid integer NOT NULL,
    songd integer NOT NULL,
    countid integer NOT NULL
    );


    insert into daily_report (date_time, userid, songd, countid) values
    (to_date('2017-12-31','YYYY-MM-DD'), 1 , 1 , 5),
    (to_date('2017-12-31','YYYY-MM-DD'), 2 , 1 , 10),
    (to_date('2017-12-31','YYYY-MM-DD'), 4 , 1 , 7);


    insert into summary_songs (date_time, userid, songd, countid) values
    (to_date('2017-12-30', 'YYYY-MM-DD'),1, 1, 80),
    (to_date('2017-12-30', 'YYYY-MM-DD'),2, 1, 51),
    (to_date('2017-12-30', 'YYYY-MM-DD'),3, 1, 66);

    查询 1 :
    select * from daily_report 

    Results :
    |  date_time | userid | songd | countid |
    |------------|--------|-------|---------|
    | 2017-12-31 | 1 | 1 | 5 |
    | 2017-12-31 | 2 | 1 | 10 |
    | 2017-12-31 | 4 | 1 | 7 |

    查询 2 :
    select * from summary_songs 

    Results :
    |  date_time | userid | songd | countid |
    |------------|--------|-------|---------|
    | 2017-12-30 | 1 | 1 | 80 |
    | 2017-12-30 | 2 | 1 | 51 |
    | 2017-12-30 | 3 | 1 | 66 |

    查询 3 :
    insert into summary_songs (date_time, userid, songd, countid)
    select date_time, userid, songd, countid from daily_report
    on conflict (userid, songd)
    do update set
    countid = summary_songs.countid + excluded.countid ,
    date_time = excluded.date_time

    查询 4 ​​ :
    select * from summary_songs 

    Results :
    |  date_time | userid | songd | countid |
    |------------|--------|-------|---------|
    | 2017-12-30 | 3 | 1 | 66 |
    | 2017-12-31 | 1 | 1 | 85 |
    | 2017-12-31 | 2 | 1 | 61 |
    | 2017-12-31 | 4 | 1 | 7 |

    关于sql - postgres 在冲突错误时插入 - 没有唯一或排除约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49089521/

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