简体   繁体   English

是否使用一对一的MySQL Relation?

[英]Use one-to-one MySQL Relation or not?

I have user table, and I need to expand it with author and partner data. 我有用户表,并且需要使用作者合作伙伴数据进行扩展。 Should I put additional columns in same table or create 2 more tables ( user_author and user_partner ) with one-to-one relationship ? 我应该在同一表中放置其他列还是应该以一对一的关系再创建2个表( user_authoruser_partner )?

Tables and columns are simplified for example. 例如,表和列被简化。

user 用户

id
name
email
password
avatar
is_active

user_author user_author

user_id => user.id (PK, UNQ)
description
amount_per_text
max_text
is_active

user_partner user_partner

user_id => user.id (PK, UNQ)
name
description
image_logo
is_active

User cannot be both author and partner. 用户不能同时是作者和伙伴。 And then I can have classes like User.php for normal users, UserPartner.php and UserAuthor.php which extends User.php class. 然后,我可以拥有像User.php这样的普通用户类, UserPartner.phpUserAuthor.php这样的类,它们可以扩展User.php类。

Does it make sense or should I just put those columns in user table ? 是否有意义,还是应该将这些列放在用户表中?

Both approaches are valid and frequently used. 两种方法都是有效且经常使用的。

The normalization theory of a relational schema would not allow to put all the data in a single table for reasons of data consistency. 由于数据一致性,关系模式的规范化理论不允许将所有数据放在单个表中。 This would favor a multi-table approach. 这将有利于采用多表方法。

In the single-table approach you'll end up with a lot of empty (null) fields in every record in the table. 在单表方法中,表中的每个记录最终都会有很多空(空)字段。

When using multiple tables, however, you may have to perform one or two joins just to find out if a record is a partner or an author. 但是,当使用多个表时,可能只需要执行一次或两次连接即可确定记录是合伙人还是作者。 Hence, from a performance viewpoint, the single-table solution is preferrable. 因此,从性能的角度来看,单表解决方案是可取的。

In both cases, you could include an extra field, eg "recordType", in user to quickly and easily discriminate between the different types of records. 在这两种情况下,您都可以在用户中包含一个额外的字段,例如“ recordType”,以快速,轻松地区分不同类型的记录。 This will give the best possible runtime performance. 这将提供最佳的运行时性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM