如何在mysql中建立一对多关系图,如何在数据库中建立一对多关系模型

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 |

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?

Thanks in advance.

解决方案

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

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

and propably many more.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值