数据库最佳实践 [英] Database best practices

查看:126
本文介绍了数据库最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表存储评论,评论可以来自另一个用户,或另一个配置文件,在这个应用程序中的独立实体。



我原来的想法是,该表将同时具有user_id和profile_id字段,因此如果用户提交了注释,

这是对的,错了,有更好的方法吗?

解决方案

在过去,我使用了一个集中的注释表,并且有一个fk_table引用的字段。

例如:

 评论(id,fk_id,fk_table,comment_text)

这样,您可以使用UNION查询来连接来自多个来源的数据。

  SELECT c.comment_text FROM comment c JOIN user u ON u.id = c.fk_id WHERE c.fk_table =user
UNION ALL
SELECT c.comment_text FROM comment c JOIN profile p ON p.id = c.fk_id WHERE c.fk_table =profile

这可以确保您可以扩展具有注释的对象数量,而无需创建冗余表。


I have a table which stores comments, the comment can either come from another user, or another profile which are separate entities in this app.

My original thinking was that the table would have both user_id and profile_id fields, so if a user submits a comment, it gives the user_id leaves the profile_id blank

is this right, wrong, is there a better way?

解决方案

In the past I have used a centralized comments table and had a field for the fk_table it is referencing.

eg:

comments(id,fk_id,fk_table,comment_text)

That way you can use UNION queries to concatenate the data from several sources.

SELECT c.comment_text FROM comment c JOIN user u ON u.id=c.fk_id WHERE c.fk_table="user"
UNION ALL
SELECT c.comment_text FROM comment c JOIN profile p ON p.id=c.fk_id WHERE c.fk_table="profile"

This ensures that you can expand the number of objects that have comments without creating redundant tables.

这篇关于数据库最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆