我希望标题不会太混乱——我不知道怎么称呼它。
假设您有一张产品表:
+----+---------------------------+-------+
| 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 由 1x 产品 1、2x 产品 2 和 1x 产品 3 组成。
在产品表中有一个“库存”列,表示每种产品当前有多少库存。
Q 是:如何通过一个 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;