Sql 如何使我的购物车表在postgress中正常工作?
我们试图输入的是字段,我们选择在atmept中手动插入购物车id,以便对多个项目(如商店)使用相同的购物车:Sql 如何使我的购物车表在postgress中正常工作?,sql,postgresql,database-design,Sql,Postgresql,Database Design,我们试图输入的是字段,我们选择在atmept中手动插入购物车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; 基本上,它的工作原理是,我只能有一个购物车id,但可以有多个库存id(库存id),但库存id和购物车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;
基本上,它的工作原理是,我只能有一个购物车id,但可以有多个库存id(库存id),但库存id和购物车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\u id、inventory\u id上添加一个唯一的键 : 如果没有,则可以将购物车id和库存id都设置为复合主键:
CONSTRAINT "cart_PK" PRIMARY KEY (cart_id, inventory_id)
在这种情况下,您不再需要唯一密钥
CONSTRAINT "cart_PK" PRIMARY KEY (cart_id, inventory_id)