假設我有一個「消息」表,其中我想存儲我的應用程序支持的所有可能的消息。例如,在類似FB的應用程序中,可能存在「媒體消息」(例如照片,視頻,音頻),「媒體專輯消息」,「私人消息」等。對此進行建模的一種方式是:數據庫設計:FK是NULL - 好還是壞?
Table: message
- messag_id (PK)
- user_id (FK, this is the sender of the message)
- message
TABLE: media_message
- media_message_id (PK, receiver of the message implied by the owner of the media)
- message_id (FK)
TABLE: media_album_message
- media_album_message_id (PK, receiver of the message implied by the owner of the media album)
- message_id (FK)
TABLE: private_message
- private_message_id (PK)
- message_id (FK)
- user_id (FK, receiver of the message)
... etc.
因此,對於消息的每個「類型」,我都需要創建某種「映射表」。
會是這樣的工作:
TABLE: message
- message_id (PK)
- receiver_user_id (FK)
- sender_user_id (FK)
- message
- media_album_id (FK, NULL allowed)
- media_id (FK, NULL allowed)
我覺得這個設計,我仍然可以實施參照完整性。如果media_album_id
和media_id
都是NULL,那麼我可以假設它是一個「私有」消息(或者在應用層實現一些類似的邏輯)。不利的一面,如果它甚至是一個缺點,那就是總會有不使用的列。然後再次,也許這將擴大更好 - 少JOINs等
想法?
可以使用可空的FK,並且在可選的現有關係中不存在問題。 –
拉里,你怎麼看待dportas的評論? – StackOverflowNewbie