其实我是noob,并在这个问题上停留了一个星期。我会尝试解释它。 我有用于USER的表, 和产品表 我想存储每个产品的每个用户的数据。像if_product_bought,num_of_items和所有。如何在数据库中创建数据库(postgres)?
所以只有解决方案我能想到数据库内的数据库,即在用户命名数据库内创建一个产品副本并开始存储。
如果这是可能如何或是否有任何其他更好的解决方案提前 感谢
其实我是noob,并在这个问题上停留了一个星期。我会尝试解释它。 我有用于USER的表, 和产品表 我想存储每个产品的每个用户的数据。像if_product_bought,num_of_items和所有。如何在数据库中创建数据库(postgres)?
所以只有解决方案我能想到数据库内的数据库,即在用户命名数据库内创建一个产品副本并开始存储。
如果这是可能如何或是否有任何其他更好的解决方案提前 感谢
你居然不创建database
内的database
(或table
内的table
)当您使用PostgreSQL或任何其他SQL RDBMS。
你使用tables
和JOIN
他们。您通常会在users
和items
之上有orders
表格和items_x_orders
表格。
这是一个非常简单的场景:
CREATE TABLE users
(
user_id INTEGER /* SERIAL */ NOT NULL PRIMARY KEY,
user_name text
) ;
CREATE TABLE items
(
item_id INTEGER /* SERIAL */ NOT NULL PRIMARY KEY,
item_description text NOT NULL,
item_unit text NOT NULL,
item_standard_price decimal(10,2) NOT NULL
) ;
CREATE TABLE orders
(
order_id INTEGER /* SERIAL */ NOT NULL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(user_id),
order_date DATE NOT NULL DEFAULT now(),
other_data TEXT
) ;
CREATE TABLE items_x_orders
(
order_id INTEGER NOT NULL REFERENCES orders(order_id),
item_id INTEGER NOT NULL REFERENCES items(item_id),
-- You're supposed not to have the item more than once in an order
-- This makes the following the "natural key" for this table
PRIMARY KEY (order_id, item_id),
item_quantity DECIMAL(10,2) NOT NULL CHECK(item_quantity <> /* > */ 0),
item_percent_discount DECIMAL(5,2) NOT NULL DEFAULT 0.0,
other_data TEXT
) ;
这是所有基于在所谓的Relational Model。你在想什么叫做Hierarchical model或document model,在某些NoSQL数据库(将数据存储为JSON或XML分层结构)中使用。
你将填补这些表中包含的数据:
INSERT INTO users
(user_id, user_name)
VALUES
(1, 'Alice Cooper') ;
INSERT INTO items
(item_id, item_description, item_unit, item_standard_price)
VALUES
(1, 'Oranges', 'kg', 0.75),
(2, 'Cookies', 'box', 1.25),
(3, 'Milk', '1l carton', 0.90) ;
INSERT INTO orders
(order_id, user_id)
VALUES
(100, 1) ;
INSERT INTO items_x_orders
(order_id, item_id, item_quantity, item_percent_discount, other_data)
VALUES
(100, 1, 2.5, 0.00, NULL),
(100, 2, 3.0, 0.00, 'I don''t want Oreo'),
(100, 3, 1.0, 0.05, 'Make it promo milk') ;
然后你会产生类似下面的一个,查询,你JOIN
所有相关表格:
SELECT
user_name, item_description, item_quantity, item_unit,
item_standard_price, item_percent_discount,
CAST(item_quantity * (item_standard_price * (1-item_percent_discount/100.0)) AS DECIMAL(10,2)) AS items_price
FROM
items_x_orders
JOIN orders USING (order_id)
JOIN items USING (item_id)
JOIN users USING (user_id) ;
...并获得这些结果:
user_name | item_description | item_quantity | item_unit | item_standard_price | item_percent_discount | items_price :----------- | :--------------- | ------------: | :-------- | ------------------: | --------------------: | ----------: Alice Cooper | Oranges | 2.50 | kg | 0.75 | 0.00 | 1.88 Alice Cooper | Cookies | 3.00 | box | 1.25 | 0.00 | 3.75 Alice Cooper | Milk | 1.00 | 1l carton | 0.90 | 5.00 | 0.86
你可以得到所有的代码和测试dbfiddle here