私はpostgreSQLについてはかなり新しくなっていますが、データを相互参照する標準的な方法を理解しようとしています。例として、次のコードを取る:postgreSQLの相互参照ですか?
次の出力を生成しDROP TABLE IF EXISTS order_items;
DROP TABLE IF EXISTS products;
DROP TABLE IF EXISTS orders;
CREATE TABLE products(
product_id SERIAL PRIMARY KEY,
name TEXT,
price NUMERIC(5,2)
);
CREATE TABLE orders(
order_id SERIAL PRIMARY KEY,
address TEXT
);
CREATE TABLE order_items(
product_id INT REFERENCES products,
order_id INT REFERENCES orders,
quantity INT
);
INSERT INTO products(name, price) VALUES('socks', 4.98), ('shoes', 20.21), ('hats', 12.54);
INSERT INTO orders(address) VALUES('California'), ('New York');
INSERT INTO order_items VALUES(1, 1, 4);
INSERT INTO order_items VALUES(2, 1, 2);
INSERT INTO order_items VALUES(3, 1, 1);
INSERT INTO order_items VALUES(1, 2, 3);
INSERT INTO order_items VALUES(3, 2, 1);
SELECT order_id, product_id, quantity FROM order_items;
:
order_id | product_id | quantity
----------+------------+----------
1 | 1 | 4
1 | 2 | 2
1 | 3 | 1
2 | 1 | 3
2 | 3 | 1
を、私は単一の文のうち、これを作る方法を知りたい:
orders.address | products.name | products.price | order_items.quantity
----------------+---------------+----------------+----------------------
California | socks | 4.98 | 4
California | shoes | 20.21 | 2
California | hats | 12.54 | 1
New York | socks | 4.98 | 3
New York | hats | 12.54 | 1
私は解決策が何とかWITH
を使用することを含むかもしれないと思うが、私は確信していない。
ありがとうございます。
量として価格、合計(数量)として 'MAX(価格)を使用する利点は何ですか、このような何か住所、名前、価格、数量で 'over'グループ?私たちは主キーに基づいてそれらを結合しているので、それが1つの値の合計になることはわかっています。それとも、それは味の問題ですか? –
ああ、あなたは正しいと思います。私は間違って、少なくとも量の合計を適用する必要があると仮定していたと思います。 – scottjustin5000