Can phone number be used as a primary key in a database: Difference between revisions

From LemonWiki共筆
Jump to navigation Jump to search
Line 16: Line 16:
* [https://zh.wikipedia.org/zh-tw/%E5%8F%82%E7%85%A7%E5%AE%8C%E6%95%B4%E6%80%A7 參照完整性]指「指在兩個資料表中,次要資料表的外鍵(FK)的資料欄位值,一定要存在於主要資料表的主鍵(PK)中的資料欄位值。」<ref>[https://www.mysql.tw/2017/04/blog-post.html 資料庫的完整性規則 - MySQL Taiwan]</ref><ref>[https://opentextbc.ca/dbdesign01/chapter/chapter-9-integrity-rules-and-constraints/ Chapter 9 Integrity Rules and Constraints – Database Design – 2nd Edition]</ref>
* [https://zh.wikipedia.org/zh-tw/%E5%8F%82%E7%85%A7%E5%AE%8C%E6%95%B4%E6%80%A7 參照完整性]指「指在兩個資料表中,次要資料表的外鍵(FK)的資料欄位值,一定要存在於主要資料表的主鍵(PK)中的資料欄位值。」<ref>[https://www.mysql.tw/2017/04/blog-post.html 資料庫的完整性規則 - MySQL Taiwan]</ref><ref>[https://opentextbc.ca/dbdesign01/chapter/chapter-9-integrity-rules-and-constraints/ Chapter 9 Integrity Rules and Constraints – Database Design – 2nd Edition]</ref>
* 當客戶的手機遺失需要更換手機號碼,原本在相關的銷售紀錄、保固維修資料表的舊有資料參照的主鍵,也要隨之異動。<ref>[https://stackoverflow.com/questions/38612677/can-we-use-any-other-unique-constraint-as-primary-key-in-database-like-a-phone-n mysql - Can we use any other unique constraint as primary key in database like a phone number, or national Id - Stack Overflow]</ref>
* 當客戶的手機遺失需要更換手機號碼,原本在相關的銷售紀錄、保固維修資料表的舊有資料參照的主鍵,也要隨之異動。<ref>[https://stackoverflow.com/questions/38612677/can-we-use-any-other-unique-constraint-as-primary-key-in-database-like-a-phone-n mysql - Can we use any other unique constraint as primary key in database like a phone number, or national Id - Stack Overflow]</ref>
'''效能議題'''
* 主鍵使用手機號碼的話,第一碼需要補零,導致欄位資料型態是「文字」,但是使用整數可以有較好的查詢效能,


== 建議 ==
== 建議 ==

Revision as of 11:16, 20 May 2022

可以使用手機號碼或者是電話號碼,當作資料表的主鍵 (primary key) 嗎?

問題

透過識別碼可以串聯不同資料,那麼可以將客戶手機號碼當作不同資料表,例如銷售紀錄、保固維修服務間的主鍵嗎?

技術思考

獨特不重複

  • 以手機號碼為例,如果是個人聯絡用還 OK,因為經驗上個人不會時常換門號。
  • 但是如果是客戶公司業務的手機,則會需要考慮到日後業務換人的話,要怎麼處理資料異動。

維護「參照完整性」規則

  • 參照完整性指「指在兩個資料表中,次要資料表的外鍵(FK)的資料欄位值,一定要存在於主要資料表的主鍵(PK)中的資料欄位值。」[1][2]
  • 當客戶的手機遺失需要更換手機號碼,原本在相關的銷售紀錄、保固維修資料表的舊有資料參照的主鍵,也要隨之異動。[3]

效能議題

  • 主鍵使用手機號碼的話,第一碼需要補零,導致欄位資料型態是「文字」,但是使用整數可以有較好的查詢效能,

建議

主鍵的設計會考慮資料本身有沒有獨特不重複的屬性,並且不可是 NULL 值,如果沒有獨特不重複的屬性,則使用資料庫本身內建的自動增加的流水號。(參考資料:MySQL 文件[4]

  • 思考客戶資料本身有沒有獨特不重複的屬性
  • 使用資料庫引擎支援的自動增加的流水號 (auto-increment values)

參考資料


Further reading