2011-11-13 40 views
1

我已經提到我需要並自動遞增id以跟蹤唯一記錄... ...基本上...指向PRIMARY KEY一個自動遞增int在主鍵和自動遞增的上下文中實現INDEX字段int

我可以看到這一點,因爲用戶數據是可變的..它的變化...如果你給每一行一個ID,它可以作爲一種方式來更好地跟蹤用戶,並且不佔用太多很多空間 - 4個字節。

我還聽說過該索引字段被用來作爲一種方法可以做到加快搜索速度..

如果我有一組用戶屬性的說,A1, A2, A3,我有一個主鍵,P,定義爲一個int I ... INDEX如何與此相關?我如何正確實施它?

列 -

int, varchar, varchar, varchar,....Primary Key, Index ? 

I, A1, A2, A3..., P, ? 

回答

1

在MySQL:

  • 主鍵是索引
  • AUTO_INCREMENT列必須是主鍵
  • KEY是INDEX
  • 的同義詞

所以在你的例子中I將因此然而被宣佈

CREATE TABLE (
    I int NOT NULL AUTO_INCREMENT, 
    ... 
    PRIMARY KEY (I) 
    ... 

,這是一個「代孕」的關鍵,因爲它不是自然鍵(如員工編號),因此你必須對過於

唯一索引(或鑰匙)
CREATE TABLE ( ... 
    EmployeeNumber char(7) NOT NULL, 
    ... 
    UNIQUE KEY (EmployeeNumber) 
    ... 

根據JOIN和WHERE中的用法,可以在單個列或列組合上創建其他索引,但索引策略通常與爲表選擇主鍵不同。

+0

O.K所以如果我定義了一些主鍵,我可以放心,當我對它進行搜索時..那麼這個搜索是有效的..即。數據被放入B樹中,如此處所述 - http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html –

+0

它將被編入索引? –

+0

我不想使用代理鍵...只是想用你的第一個例子..是這個O.K.? –

0

聽起來像你有1:M的關係,因爲用戶可以有很多屬性。我建議第2個表中存儲的屬性與外鍵返回到用戶表:

create table `user` (
    `id` int(11) unsigned not null auto_increment, 
    `first_name` varchar(60) not null, 
    primary key (`id`) 
)engine=InnoDB default charset=utf8; 

create table `user_attribute_link` (
    `id` int(11) unsigned not null auto_increment, 
    `user_id` int(11) unsigned not null, 
    `attribute_id` int(11) unsigned not null,  
    primary key (`id`), 
    index (`user_id`, `attribute_id`), 
    foreign key (`user_id`) references `user` (`id`) on delete cascade 
    foreign key (`attribute_id`) references `user_attribute` (`id`) on delete cascade 
)engine=InnoDB default charset=utf8; 

create table `user_attribute` (
    `id` int(11) unsigned not null auto_increment, 
    `name` varchar(60) not null, 
    primary key (`id`), 
    unique key (`name`), 
)engine=InnoDB default charset=utf8; 

如果從用戶刪除一行,從任何子行從用戶表到user_attribute表中的FK將確保user_attribute也將被刪除。唯一鍵也被添加到屬性表中,以確保您無法添加任何重複屬性。

編輯 用支持M:M(通過1:M-M:1)的第3表更新了模式。如果您需要爲用戶屬性添加更多信息,這將提供更大的靈活性。

+0

如果屬性具有不同的類型,這會變得很難看,因爲它會變成EAV http://karwin.blogspot.com/2009/ 05/eav-fail.html或http://programmers.stackexchange.com/questions/93124/eav-is-is-really-bad-in-all-scenarios – gbn

+0

@gbn:同意,提供基於OP的解決方案,但我更新了架構以支持用戶屬性的靈活性。 –

相關問題