使用具有值

时间:2017-10-13 10:30:21

标签: mysql sql database

我正在开发一个系统,我需要创建一个应该能够具有零个或多个可配置属性的“根对象”。

让我们说它是客户,我们总是知道我们要存储customerId,name和birthdate - 这将是表中的列。但系统应该能够为客户处理自定义属性。

假设系统用户还希望为该客户存储城市,电话和电子邮件。我如何以最佳方式为数据库建模?

这就是我在表格方面的想法:

Customer
 - CustomerId
 - Name
 - Birthdate

CustomerProperties
 - CustomerPropertyId
 - Name

CustomerPropertyValues
 - Id
 - CustomerId
 - CustomerPropertyId
 - Value

通过此设置,“City”将成为“CustomerProperties”表中的CustomerProperty,该属性的值将作为条目存储在CustomerPropertyValues表中。

这样我就可以使用SQL查询X市的所有客户。

我一直在考虑将所有自定义属性存储为json blob,但这会使查询变得非常困难,我猜这不会有好处。

我想知道的是:这是我的db-modol示例一个好方法吗?有没有更好的方法来模拟这个?在这方面的性能,挑战等方面我应该“注意”什么?

感谢您提供任何帮助或反馈!

1 个答案:

答案 0 :(得分:2)

我必须在很多场合做类似的事情,我自己的易用性,可维护性和健壮性的方法是:

Customer
 - CustomerId
 - Name
 - Birthdate

CustomerProperties
 - CustomerPropertyId
 - CustomerId
 - Name
 - DataType
 - Value

根据您希望保留的记录数和不同类型的数据,您可能希望通过为每种数据类型添加单独的表来对其进行标准化:

Customer
 - CustomerId
 - Name
 - Birthdate

CustomerDateTimeProperties
 - CustomerPropertyId
 - CustomerId
 - Name
 - Value

CustomerIntegerProperties
 - CustomerPropertyId
 - CustomerId
 - Name
 - Value

CustomerStringProperties
 - CustomerPropertyId
 - CustomerId
 - Name
 - Value

然后可以设置Value字段数据类型,并避免所有类型转换。 这些是过去最适合我的方法,我希望这会有所帮助。

获取客户的所有属性:

SELECT * FROM Customer, CustomerDateTimeProperties, CustomerIntegerProperties
INNER JOIN CustomerDateTimeProperties ON CustomerDateTimeProperties.CustomerId = Customer.CustomerId
INNER JOIN CustomerIntegerProperties ON CustomerIntegerProperties .CustomerId = Customer.CustomerId

INNER JOIN etc...

WHERE Customer.CustomerId = @CustomerId

如果您正在使用我的第一个示例,只需使用一个连接到CustomerProperties表。