数据建模:使用一系列 BOOL 还是 1 个 ENUM?

发布于 2024-10-29 14:12:31 字数 491 浏览 0 评论 0原文

假设我有一个名为“media”的表来表示音频、图像和视频。此外,假设我需要区分媒体类型。哪个更好:

TABLE: media
 - media_id
 - is_audio (BOOL)
 - is_image (BOOL)
 - is_video (BOOL)

或者

TABLE: media
 - media_id
 - type (ENUM: "audio", "image", "video")

如果有 1000 种媒体类型怎么办?我是否将模型分成 2 个表:

TABLE: media
 - media_id
 - media_type_id

TABLE: media_type
 - media_type_id
 - name*
  • 注意:假设确实不需要知道媒体类型的“名称”(例如,您需要知道它是图像,但不在乎它是 JPG)。

Say I have a table called "media" to represent audios, images, and videos. Furthermore, say I need to distinguish between the media types. Which is better:

TABLE: media
 - media_id
 - is_audio (BOOL)
 - is_image (BOOL)
 - is_video (BOOL)

OR

TABLE: media
 - media_id
 - type (ENUM: "audio", "image", "video")

What if there were 1000 media types? Do I split the model into 2 tables:

TABLE: media
 - media_id
 - media_type_id

TABLE: media_type
 - media_type_id
 - name*
  • NOTE: say there really is no need to know the "name" of the media type (e.g. you need to know it's an image, but don't care that it's a JPG).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

药祭#氼 2024-11-05 14:12:32

第三个选项——使用参考表——可能是最广泛支持的,也是我经常使用的。

使用第三个选项,如果 mediaTypeId 列是 MediaType 表的外键,则可以保证数据完整性(除非您使用的 SQL 风格不支持强制外键,例如带有 MyISAM 引擎的 SQLite 或 MySQL)。

您的第一个解决方案无法实现这一点 - 您可能会在该表中将 is_audiois_image 设置为 1 的记录。此外,当您添加更多媒体类型时,您的表格会变得更宽、更丑、更笨重。

您的第二个选项(使用枚举)似乎特定于 MySQL(如果您不打算使用除 MySQL 之外的任何东西,那么这是可以的)。从它的文档页面来看,它实际上是一个字符串类型(不必要但比整数稍微占用更多空间),并且添加新选项似乎非常痛苦(请参阅 这个问题)。此外,如果您希望其他表引用媒体类型,它们都需要自己的枚举。

我会选择第三个选项,它更便携,并且它也允许其他表引用 MediaType

Your third option – using a reference table – is probably the most widely supported, and it's what I regularly use.

With the third option, if the mediaTypeId column is foreign keyed to the MediaType table, you have guaranteed data integrity (unless you're using a flavor of SQL that doesn't enforce foreign keys, such as SQLite or MySQL with the MyISAM engine).

You don't get that with your first solution — you could potentially have a record in that table that has both is_audio and is_image set to 1. Additionally, as you add more media types, your table becomes wider, uglier, and clunkier.

Your second option (using enums) seems to be specific to MySQL (which is okay if you don't ever plan to use anything but MySQL). From its documentation page, it's actually a string type (which needlessly yet slightly takes up more space than an integer), and it seems very painful to add new options (see this question). Additionally, if you want other tables to reference media types, they all need their own enums.

I'd go with your third option, which is more portable, and it allows other tables to reference MediaType as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文