CREATE TABLE products (
product_id integer PRIMARY KEY,
product_name text,
price numeric);
INSERT INTO products (product_id, product_name, price) VALUES
(DEFAULT, 'Purple Widget', '5.50'),
(DEFAULT, 'Green Widget', '1.50'),
(DEFAULT, 'Yellow Widget', '5.50'),
(DEFAULT, 'Spotted Widget', '6.50'),
(DEFAULT, 'Extra Large Purple Widget', '102.50'),
(DEFAULT, 'Extra Large Spotted Widget', '101.50');
我想开始销售一揽子产品(多种产品,一种价格)。我试图找出一个包表的结构。我不喜欢的两个选项是 -
CREATE TABLE packages (
package_id integer PRIMARY KEY,
package_name text,
package_products varchar(50),
price numeric);
INSERT INTO packages (package_id, package_name, package_products, price) VALUES
(DEFAULT, 'Small Widgets', '0,1,2,3', '6.25'),
(DEFAULT, 'Large Widgets', '5,6', '200.00');
或
CREATE TABLE packages (
package_id integer PRIMARY KEY,
package_name text,
product_id1 integer,
product_id2 integer,
product_id3 integer,
product_id4 integer,
product_id5 integer,
price numeric);
INSERT INTO packages (package_id, package_name, product_id1, product_id2,
product_id3, product_id4, product_id5, price) VALUES
(DEFAULT, 'Small Widgets', '0', '1' ,'2', '3', NULL, '6.25'),
(DEFAULT, 'Large Widgets', '5', '6', NULL, NULL, NULL, '200.00');
我无法将包逻辑移动到products表,因为每个产品可能位于多个包中。上述两个选项都需要在Web层进行大量工作才能完成工作,而且它们看起来效率都很低。
想法?提前谢谢!
答案 0 :(得分:4)
这是一个标准的many-to-many关系(许多项目的许多包)
CREATE TABLE products (
product_id integer PRIMARY KEY,
product_name text,
price numeric);
CREATE TABLE packages (
package_id integer PRIMARY KEY,
package_name text,
price numeric);
CREATE TABLE package_items (
package_item_id integer PRIMARY KEY,
package_id integer,
product_id integer,
qty integer );
答案 1 :(得分:4)
另请注意,应将外键约束放在引用其他表中行的列上。
CREATE TABLE PackageProduct (
product_id integer,
package_id integer,
FOREIGN KEY (product_id) REFERENCES Product(product_id),
FOREIGN KEY (package_id) REFERENCES Package(package_id));
答案 2 :(得分:1)
Package表和PackageProduct表怎么样?
CREATE TABLE Product (
product_id integer PRIMARY KEY,
product_name text,
price numeric);
CREATE TABLE Package (
package_id integer PRIMARY KEY,
package_name text
price numeric);
CREATE TABLE PackageProduct (
product_id integer,
package_id integer);
然后只需将您的包添加到包表中,并将包中每个产品的行添加到PackageProduct表中。