如何在关系数据库中存储对象? [英] How to store objects in a relational database?

查看:74
本文介绍了如何在关系数据库中存储对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之前有人问过类似的问题,但没有人回答.如何在关系数据库中存储值对象?

Someone asked a similar question before, but it wasn't answered. How to store value objects in a relational database?

这是我的问题发挥作用的示例情况.假设有一个用户"表,每个用户都需要存储他们的位置.它们的位置基本上只有 3 个坐标:x、y、z.

Here is an example situation where my question comes into play. Let's say there is a 'users' table, and each user needs to have their location stored. Their location is essentially just 3 coordinates: x, y, z.

但是,我不确定我应该怎么做.我可以向名为 'x, y, z' 的 'user' 行添加 3 个整数字段.

But, I'm not sure how I should be going about this. I could just add 3 integer fields to the 'user' row named 'x, y, z'.

或者,我可以向用户行添加一个位置"字符串字段,然后在获取/保存用户位置时简单地序列化和反序列化.

Or, I could add a 'location' String field to the user row, and then simply serialize and deserialize whenever I fetch/save a user's location.

或者,我可以创建一个 'locations' 表,它有一个 auto-inc 主键 id,它将用作 'users' 位置数据库的外键,它有 4 个字段:'id'、'x', 'y', 'z'.

Or, I could create a 'locations' table, that has an auto-inc primary key id, that will be used as foreign key for the 'users' location database, which would have 4 fields: 'id', 'x', 'y', 'z'.

那么,哪个最好?也许有一个我没有看到的更好的答案?谢谢.

So, which one is best? Maybe there's an answer I'm not seeing that's better? Thanks.

推荐答案

鉴于所有场景都不同,有时以微妙的方式,通常没有最佳".

There generally isn't a "best" given that all scenarios are different, sometimes in subtle ways.

但是,如果您在设计一般事物时正在寻找整体的最佳实践",我会倾向于这样:

However, if you're looking for an overall "best practice" when designing something in general, I'd lean toward this:

做最简单的事情,只在需要时增加复杂性.

Do the simplest thing possible, and only add complexity when needed.

为此,我认为 Users 表中的三个整数列是有意义的并且非常简单.您需要将数据序列化为字符串吗?毕竟,数据本身不是字符串.它是一组数值.这可能会使其他事情变得不必要地困难,不是吗?数据是否需要位于具有自己标识符的单独表中?毕竟,它本身并不是一个实体,而只是一个描述 User 的数据点.

To that end, I imagine that three integer columns in the Users table makes sense and is pretty simple. Do you need to serialize the data into a string? After all, the data itself isn't a string. It's a set of numeric values. That might make other things unnecessarily difficult, no? Does the data need to be in a separate table with its own identifier? After all, it's not really an entity in and of itself, but rather just a data point which describes a User.

除非有令人信服的理由去做更复杂的事情,否则请保持简单.

Unless there's a compelling reason to do something more complex, keep it simple.

这篇关于如何在关系数据库中存储对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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