我有 2 个 Mysql 表,如下所示:
用户:
uid uname pass email st_id
================================================
1 xxx xx xx 1, 2,3, 4
车站:
st_id st_name
================
1 xxx
2 xxx
3 xxx
4 xxx
当我添加新用户时,我需要选择多个站s,并且将 st_id
作为逗号 (,) 分隔值插入到 users
表。
这样插入st_id
是不是更好?
或
我可以将每个不同的st_id
插入到users
表中,然后在users
表中总行将为4。如下所示:
用户:
uid uname pass email st_id
================================================
1 xxx xx xx 1
1 xxx xx xx 2
1 xxx xx xx 3
1 xxx xx xx 4
但是这样冗余数据就会太多!
哪种数据库表设计最好,为什么?
最佳答案
您想要第三张 table !
create table UserStations (
UserStationId int auto_increment,
UserId int not null,
StationId int not null,
primary key (UserStationId),
unique (UserId, StationId), -- probably intended
constraint fk_userstations_user foreign key (UserId) references users(uid),
constraint fk_userstatsion_station foreign key (StationId) references stations(st_id)
);
这称为连接表。这是在关系数据库中表示多对多关系的正确方法。
错误的方法是使用分隔的 ID 列表。为什么?
- 应使用适当的类型存储值。您将数字存储为整数。
- 列应包含单个值,而不是列表。
- 应显式声明外键关系。
- SQL 对字符串类型的支持不强。
- 对字段的查询无法利用索引。
- 字符串中的值列表很难保持唯一性。
关于php - 设计彼此相关的mysql表的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40960784/