2016-12-04 73 views
0

我有2代MySQL表其是波纹管:什么是设计相互关联的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是否更好?

OR

我可以将每个不同的st_idusers表,然后在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 

但这方式会造成太多冗余数据!

哪个数据库表格设计最好,为什么?

回答

2

你想要第三张桌子!

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对字符串类型没有很强的支持。
  • 字段上的查询无法利用索引。
  • 唯一性很难用字符串中的值列表维护。
+0

是的,这是一个很好的答案。 –

相关问题