如何在PostgreSQL中创建按store_id限定URL唯一性的表?
问题解决:PostgreSQL 实现同一店铺下URL唯一的约束
当前报错的核心原因是你给products表的url字段设置了单列唯一约束,这会强制整个表中所有行的url值全局唯一,完全忽略store_id的差异。要实现「同一store_id下URL不允许重复,不同store_id允许使用相同URL」的需求,只需要将单列唯一约束替换为store_id与url的联合唯一约束即可,PostgreSQL原生支持这种约束类型。
具体操作步骤
- 先删除原有的单列唯一约束:
ALTER TABLE products DROP CONSTRAINT product_url_key;
(注:product_url_key是PostgreSQL自动生成的约束名,若你手动修改过约束名称,请替换为对应的值)
- 添加
store_id和url的联合唯一约束:
ALTER TABLE products ADD CONSTRAINT unique_store_url UNIQUE (store_id, url);
你也可以直接在创建products表时就定义好联合唯一约束,修改后的建表语句如下:
CREATE TABLE products ( id SERIAL, store_id INTEGER NOT NULL, title TEXT, image TEXT, url TEXT, added_date timestamp without time zone NOT NULL DEFAULT NOW(), PRIMARY KEY(id, store_id), CONSTRAINT unique_store_url UNIQUE (store_id, url) -- 新增联合唯一约束 );
效果验证
- 插入不同
store_id的相同URL:
INSERT INTO products (store_id, url) VALUES (1, 'http://pythonisthebest.com'); INSERT INTO products (store_id, url) VALUES (2, 'http://pythonisthebest.com');
执行成功,不会返回重复键错误。
- 插入同一
store_id的相同URL:
INSERT INTO products (store_id, url) VALUES (1, 'http://pythonisthebest.com'); INSERT INTO products (store_id, url) VALUES (1, 'http://pythonisthebest.com');
执行后会返回预期的重复键错误:
ERROR: duplicate key value violates unique constraint "unique_store_url"
内容的提问来源于stack exchange,提问作者PythonNewbie
相关产品推荐
相关产品推荐

