2016-12-04 76 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

是的,這是一個很好的答案。 –

相關問題