忍受我,我真的很难解释事情,我甚至不知道这个问题的适当标题
好吧,我有这个问题
我已经有一个表名meal
+------+--------+-----------+---------+
| id | name | serving | price |
+------+--------+-----------+---------+
| 1 | soup1 | 2 person | 12.50 |
+------+--------+-----------+---------+
| 2 | soup2 | 2 person | 15.50 |
+------+--------+-----------+---------+
| 3 | soup3 | 2 person | 23.00 |
+------+--------+-----------+---------+
| 4 | drink1 | 2 person | 4.50 |
+------+--------+-----------+---------+
| 5 | drink2 | 2 person | 3.50 |
+------+--------+-----------+---------+
| 6 | drink3 | 2 person | 5.50 |
+------+--------+-----------+---------+
| 7 | frui1 | 2 person | 3.00 |
+------+--------+-----------+---------+
| 8 | fruit2 | 2 person | 3.50 |
+------+--------+-----------+---------+
| 9 | fruit3 | 2 person | 4.50 |
+------+--------+-----------+---------+
好了,现在我想让管理员从这个meal
表格中创建一个组合餐
所以这意味着,组合餐可以有无限数量的餐费
目前即时通讯如何存储/链接组合餐到餐 我不想存储下面的东西
+------+--------------+-----------+-----------+
| id | combo_name | serving | meal_id |
+------+--------------+-----------+-----------+
| 1 | combo1 | 2 person | 1,4,7,9 |
+------+--------------+-----------+-----------+
| 2 | combo2 | 2 person | 2,5,8 |
+------+--------------+-----------+-----------+
| 4 | combo3 | 2 person | 3,5,6,9 |
+------+--------------+-----------+-----------+
查看meal_id
列,我不认为这是存储数据的好方法
答案 0 :(得分:20)
创建多对多链接表:
combo_id meal_id
1 1
1 4
1 7
1 9
2 2
2 5
2 8
3 3
3 5
3 6
3 9
选择给定组合的所有餐点:
SELECT m.*
FROM combo_meal cm
JOIN meal m
ON m.id = cm.meal_id
WHERE cm.combo_id = 1
答案 1 :(得分:4)
没有。这绝对不是存储数据的好方法。使用combo_header
表和combo_details
表格会更好。
combo_header
将类似于:
+------+--------------+-----------+
| id | combo_name | serving |
+------+--------------+-----------+
| 1 | combo1 | 2 person |
+------+--------------+-----------+
| 2 | combo2 | 2 person |
+------+--------------+-----------+
| 4 | combo3 | 2 person |
+------+--------------+-----------+
然后,combo_details
将是:
+------+-----------+
| id | meal_id |
+------+-----------+
| 1 | 1 |
+------+-----------+
| 1 | 4 |
+------+-----------+
| 1 | 7 |
+------+-----------+
| 1 | 9 |
+------+-----------+
... / you get the idea!
顺便说一句,通过在单个列中使用多个值,您违反了第一个正常形式的关系数据库。
我提议的方式会让你回答像这样的查询,让所有的combo1 的名字都很容易解决。
答案 2 :(得分:1)
这被称为膳食和组合之间的多对多关系。一餐可以多个组合列出,组合可以包含多餐。您将需要一个包含所有可能的膳食组合对的链接表(而不是combo.meal_id字段)。
最后,您将有三个表:
meal_combo.autoid并非严格需要,只是一般性建议。
列出一个包含所有食物的组合:
SELECT meal.id, meal.name FROM comboINNER JOIN meal_combo ON meal_combo.combo_id = combo.id INNER JOIN meal ON meal.id = meal_combo.meal_id WHERE combo.id = 132
Google提供“多对多关系”或“数据库链接表”以获取详细信息。