mysql - 将注释表映射到 mysql 中的多个表的最佳实践是什么?

标签 mysql foreign-keys comments

我正在寻找将一个基表映射到多个表的最佳实践。例如,如果我有以下任何一个基表(评论、标签、收藏夹、评级),它可以映射到一个或多个表,例如(博客文章、图片、视频)。下面的例子可以提供更好的解释。

更多信息:
我希望使用这些表来创建一个使用 Active Record 的 Yii 应用程序。

我建议的解决方案 (Mysql):
我的基表

create table comment (
 id int(4) unsigned not null auto_increment primary key,
 attach_id int(4) unsigned not null,           #used to attach to a specific post/photo/video
 attach_type_id tinyint(1) unsigned not null,  #foreign key to attach_type(id)
 comment text not null,
 user_id int(4) unsigned null,
 datetime_added datetime not null,
 foreign key (attach_type_id) references attach_type(id)
);

我的“全局映射”表:

create table attach_type (
 id tinyint(1) unsigned not null auto_increment primary key,
 table_name varchar(20) not null  #used for reference purposes only
);

“多个”表中的两个的原始示例:

create table blog_post (
 id int(4) unsigned not null auto_increment primary key,
 title varchar(100) not null,
 post text not null,
 user_id int(4) unsigned null,
 datetime_added datetime not null
);

create table photo (
 id int(4) unsigned not null auto_increment primary key,
 title varchar(100) not null,
 description varchar(255) null,
 file_name varchar(100) not null,
 user_id int(4) unsigned null,
 datetime_added datetime not null
);

检索博客文章 id=54 的所有评论
blog_post 表在 attach_type 表中的行的 id = 1
该帖子在 blog_post 表中的行的行 ID = 54

select * from comments where attach_type_id=1 and attach_id=54;

所以上面看到的(评论,标签,收藏,评级)评论可以附加到博客帖子和/或照片上。同样,可以将多个评论附加到单个 blog_post/照片(允许多个用户发表评论)。我的问题是在 mysql 中解决这个问题的最佳方法是什么。上面的设置看起来是否正确,或者您会建议更好的方法以及原因。而且,如果使用上述解决方案,是否有人预见到任何明显的缺点?提前感谢您的回复,我只是想找出执行此操作的最佳方法。

我相信这个主题与我的问题有关,但并没有真正回答我的问题:
Database tables, one table referencing multiple unrelated tables

最佳答案

Tom H.提供了另一个问题的答案,我相信它回答了我的问题。我不知道如何给他适当的信任,但他的解决方案的链接在这里: Database tables, one table referencing multiple unrelated tables

感谢汤姆的帮助。

我仍然乐于接受建议,但考虑到上面链接中发布的信息,我认为我将采用制作多个 map 的路线。

关于mysql - 将注释表映射到 mysql 中的多个表的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4661746/

相关文章:

mysql - sql多元素选择

mysql - 对一张表的复杂SQL查询

php - 使用 Laravel 迁移创建外键时出现 MySQL 错误

postgresql - 具有外键约束的关系数据库如何摄取顺序可能错误的数据?

comments - 注释掉大块 HTML 代码是否安全?

node.js - 有没有工具可以从 CommonJS 或 node.JS 模块中提取文档/注释?

mysql - 上传站点到主机时如何设置MySQL数据库?

php - Eloquent:乘和加列,然后按结果排序

MySQL 使用外键创建表给出 errno : 150

json - 向 JSON 文件添加注释