我有两个桌子。 1。产品 2。组合
产品表具有类似(product_id,product_name)的列。
组合表具有类似(combo_id,combo_name,combo_included_products / *组合可能具有产品表中2个或更多产品的列* /)]
规则:1个组合可以有很多产品。
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之类的数据。然后问题将是编写联接查询。即
从combo联接产品打开combo.this_combo_included_products_id = product.product_id中选择combo.combo_id,combo.combo_id,product.product.id => product.product_id <=由于将有多个产品ID,因此是不可能的。
[我也在考虑编写一个脚本,在该脚本中,我将首先按原样获取组合表,然后将第三个cloumn拆分为“,”,然后运行迭代(从产品ID = this_combo_included_item_id [i]的组合中选择* <=我不确定这是个好主意,但是这可能是替代解决方案,之后需要进行一些编码。(我仍然使用phpmysql来获取数据-因此我可以在获取后进行处理。)
$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";
}
然而,在设计数据库表时我还能做些其他事情。谢谢。
不要在一行中存储多个值。不要将数字存储为字符串。对famous SO question的公认答案可以很好地了解其严重程度。
您在产品和组合之间具有多对多关系。表示它的正确方法是创建另一个表,称为brdige表,以存储关系。
create table product_combo (
product_id int references product(product_id),
combo_id int references combo(combo_id),
primary key (product_id, combo_id)
);