2017-07-15 123 views
0

其實我是noob,並在這個問題上停留了一個星期。我會嘗試解釋它。 我有用於USER的表, 和產品表 我想存儲每個產品的每個用戶的數據。像if_product_bought,num_of_items和所有。如何在數據庫中創建數據庫(postgres)?

所以只有解決方案我能想到數據庫內的數據庫,即在用戶命名數據庫內創建一個產品副本並開始存儲。

如果這是可能如何或是否有任何其他更好的解決方案提前 感謝

回答

1

你居然創建database內的database(或table內的table)當您使用PostgreSQL或任何其他SQL RDBMS。

你使用tablesJOIN他們。您通常會在usersitems之上有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 modeldocument 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