properties table pattern vs storing all properties in json column [duplicate]

一个人想着一个人 提交于 2019-12-07 04:35:28

As long as you don't try to use the properties for searching or sorting, there's not much difference.

As you said, putting a JSON column in your model table allows you to avoid a JOIN to the properties table.

I think your properties table actually needs to have one more column, to name the property. So it should be:

key (string), 
property (string),
value(string), 
type (string) - tells if the value is of string, integer, boolean, json type 

The downsides are pretty similar for both solutions.

  • Queries will be more complex with either solution, compared to querying normal columns.

  • Storing non-string values as strings is inefficient. It takes more space to store a numeric or datetime value as a string than as a native data type.

  • You can't apply constraints to the properties. No way to make a property mandatory (you would use NOT NULL for a normal column). No way to enforce uniqueness or foreign key references.

There's one case I can think of that gives JSON an advantage. If one of your custom properties is itself multi-valued, there's a straightforward way to represent this in JSON: as an array within your JSON document. But if you try to use a property table, do you store multiple rows for the one property? Or serialize the set of values into an array on one row? Both solutions feel pretty janky.

Because the "schemaless properties" pattern breaks rules of relational database design anyway, there's not much you can do to "do it right." You're choosing the lesser of two evils, so you can feel free to use the solution that makes your code more convenient.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!