问题描述
我有一个数据库,其中包含使用外键指示表之间关系的表。在一个表中,我有2列。.
1是id(外键),其他包含friendsid(朋友表中的外键)。
I have a database containing tables using foreign keys to indicate relationships among them. In one table I have 2 columns..1 is id (foreign key) and other contains friendsids (foreign key from friends table).
我可以将朋友放在单独的行上:
Either I can put the friends on separate rows:
| id | friendsids |
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
或将它们打包到单个字符串字段中:
Or pack them into a single string field:
| id | friendsids |
| 1 | 3,4,5 |
在第二种方式中,我将使用PHP explode()分隔Friendsid。
。还记得我有很多记录。哪种方法更有效?为什么?
In second way later I will separate friendsids using PHP explode()
. Also do remember I have lots of records. Which way is more efficient and why?
预先感谢。
推荐答案
忘记在PHP中拆分。您正在执行的是所谓的映射表,它实际上应该是1:1。这样一来,
Forget about splitting in PHP. What you are doing is a so-called mapping-table, and it really should be 1:1. That allows you to
- 轻松插入IGNORE即可添加一个映射,而无需检查映射是否已存在,
- 轻松删除映射而无需检查映射是否已存在
- 轻松计算(*)个朋友的数量,
- 轻松加入复杂查询的数据
- 使用横跨两行的UNIQUE-INDEX并快速查找数据,后者上的非唯一性
- 将数字另存为数字节省大量内存和磁盘I / O的字符串
- easily INSERT IGNORE to add a mapping w/o checking if it already exists,
- easily DELETE a mapping w/o checking if it already exists,
- easily COUNT(*) the number of friends,
- easily JOIN data for complex queries
- search your data really fast with a UNIQUE-INDEX spanning both rows and a nonunique on the latter
- save digits as digits instead of a string saving lots of ram and disk i/o
甚至更多。
这篇关于如何在数据库中建立一对多关系模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!