sql - 如何使我的购物车表在 postgress 中正常工作?
问题描述
我们尝试输入的是字段,我们选择在 atmept 中手动插入 cart_id,以便将同一个购物车用于多个项目,例如商店:
BEGIN;
INSERT INTO cart_tb(cart_id, inventory_id, desired_amount, row_status)
VALUES
(1, 1, 2, 1),
(2, 3, 1, 1),
(2, 1, 1, 1);
END;
基本上它应该如何工作是我只能有 1 个 cart_id 但有多个库存 id (inv_id),但 Inv_id 和 cart_id 的组合应该是唯一的,所以我可以拥有不同的购物车,它们可以像在现实世界中一样拥有相同的物品。这是我当前的表:
CREATE TABLE public.cart_tb
(
cart_id integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
inventory_id integer NOT NULL,
desired_amount integer NOT NULL,
row_status integer NOT NULL,
CONSTRAINT "cart_PK" PRIMARY KEY (cart_id),
CONSTRAINT "cart_UK" UNIQUE (cart_id, inventory_id),
CONSTRAINT "cart_inventory_FK" FOREIGN KEY (inventory_id)
REFERENCES public.inventory_tb (inventory_id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
TABLESPACE pg_default;
ALTER TABLE public.cart_tb
OWNER to postgres;
关于如何解决这个问题的任何建议?我一直遇到关键冲突..
ERROR: duplicate key value violates unique constraint "cart_PK"
DETAIL: Key (cart_id)=(2) already exists.
SQL state: 23505
解决方案
好的,您似乎需要一个复合主键,但我建议添加一个 id 并将其设为主键,并在 cart_id、inventory_id 上添加一个唯一键:
CREATE TABLE public.cart_tb
(
cart_id_pk integer NOT NULL GENERATED BY DEFAULT AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
cart_id integer not null,
inventory_id integer NOT NULL,
desired_amount integer NOT NULL,
row_status integer NOT NULL,
CONSTRAINT "cart_PK" PRIMARY KEY (cart_id_pk),
CONSTRAINT "cart_UK" UNIQUE (cart_id, inventory_id),
CONSTRAINT "cart_inventory_FK" FOREIGN KEY (inventory_id)
REFERENCES public.inventory_tb (inventory_id) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)
如果没有,您可以将 cart_id、inventory_id 都设置为复合主键:
CONSTRAINT "cart_PK" PRIMARY KEY (cart_id, inventory_id)
在这种情况下,您不再需要唯一键。
推荐阅读
- javascript - 无法读取未定义的属性“标签”
- c++ - 非类型模板参数和要求
- mysql - 查询内连接3张表
- python - 调用带有参数的.Net函数形式python(通过引用传递)
- java - 所有后续 servlet 请求都可以立即写入 ConcurrentHashMap 吗?
- sql - 将复杂的 Pivot SQL 查询转换为 Laravel Eloquent 关系
- javascript - 我对 Firebase .setBackgroundMessageHandler 的调用有什么问题?
- python-3.x - python 3 - 为什么在寻找最大 ord() 值时 for 循环不起作用?
- python - 如何在泛型类的 __init__ 中使用默认值?
- vba - 如何在 MS Access 中比较 2 个表单的值?