【发布时间】:2020-09-16 10:30:37
【问题描述】:
我有两张桌子。 1.产品 2.组合
产品表有类似 (product_id, product_name) 的列。
组合表有类似的列 (combo_id, combo_name, combo_included_products /* 组合可能有来自产品表的 2 个或更多产品*/)
规则:1个Combo可以有很多产品。
Product Table
product_id product_name
1 Pen
2 Pencil
3 Pen Holders
4 Sharpeners
-
Combo Table
combo_id combo_name this_combo_includes_below_products
1 Big_combo (1,2,3,4) => big combo includes all products
2 Small_combo (2,4) => this combo only includes product 2,4
3 test_combo (1,2)
4 Other_combo (1,4)
那么如何在组合表的第三列中插入多个产品 ID?
我正在考虑存储 1,2,3,4 和 2,4 等数据。那么问题将是编写连接查询。即
select combo.combo_id, combo.combo_name, product.product.id from combo join product ON combo.this_combo_included_products_id = product.product_id
我也在考虑制作一个脚本,我将首先按原样获取组合表,然后我将用“,”分割第三个 cloumn 并运行迭代 (select * from combo where product id=this_combo_included_item_id[i ])
$sql = "SELECT * FROM combo";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
// I can run other query here
$child_query = "select combo.combo_id, combo.combo_name, product.product.id from combo join product
ON combo.this_combo_included_products_id = product.product_id";
}
但是在设计数据库表时我还能做些什么。谢谢。
【问题讨论】:
-
阅读"Is storing a delimited list in a database column really that bad?" 并使用第三个表格链接产品和组合。
标签: php mysql sql database-design foreign-keys