タイトルが混乱しすぎていないことを願っています-これをどのように呼ぶかわかりません。
製品のテーブルがあるとします。
+----+---------------------------+-------+
| id | name | stock |
+----+---------------------------+-------+
| 1 | 1. Product of set | 2 |
| 2 | 2. Product of set | 5 |
| 3 | 3. Product of set | 3 |
| 4 | Set of Product 1, 2 and 3 | 0 |
+----+---------------------------+-------+
商品1~3は単品販売も可能ですが、セット販売も可能です(商品4)。したがって、別のテーブルがあります。
+---------+-------------+-------+
| product | set_product | count |
+---------+-------------+-------+
| 1 | 4 | 1 |
| 2 | 4 | 2 |
| 3 | 4 | 1 |
+---------+-------------+-------+
... これは、製品 4 が 1 つの製品 1、2 つの製品 2、および 1 つの製品 3 で構成されていることを示しています。
products-table には、各製品の現在の在庫数を示す「在庫」列があります。
Q: 1 つの SELECT で製品 4 の在庫を取得するにはどうすればよいですか (もちろん、製品 1 ~ 3 の在庫に依存します)。
テストケースをセットアップするために、次のコードを作成しました。
CREATE TABLE products (
`id` int unsigned NOT NULL AUTO_INCREMENT, unique key(id),
`name` TINYTEXT,
`stock` int NOT NULL DEFAULT 0
);
CREATE TABLE sets (
`product` int unsigned NOT NULL,
`set_product` int unsigned NOT NULL,
`count` int NOT NULL
);
INSERT INTO products SET id=1, name="1. Product of set", stock=2;
INSERT INTO products SET id=2, name="2. Product of set", stock=5;
INSERT INTO products SET id=3, name="3. Product of set", stock=3;
INSERT INTO products SET id=4, name="Set of Product 1, 2 and 3";
INSERT INTO sets SET product=1, set_product=4, count=1;
INSERT INTO sets SET product=2, set_product=4, count=2;
INSERT INTO sets SET product=3, set_product=4, count=1;