我是否违反了在 PostgresQL 中使用数组数据类型的 2NF 规则?

Am I breaking 2NF rule for using array data type in PostgresSQL?

我有一个 Users table,汽车所有权表示为 array of integers(外键)。就我个人而言,使用数组数据类型比将此 table 规范化为 2NF 要容易得多,因为在我的业务逻辑中我可以通过查询 Cars table 分别 iterate/fetch 每辆车需要。但是,我在这里的重点不是实施细节,而是 最佳实践潜在陷阱 在 RDBM 系统中使用数组数据类型。

Users table
╔════════╦══════╦═════════╗
║ userId ║ name ║ carsOwn ║
╠════════╬══════╬═════════╣
║    1   ║ Jon  ║ {2}     ║
║    2   ║ Yang ║ {1,3,4} ║
║    3   ║ Ali  ║ {1,4}   ║
║    4   ║ Kate ║ {1,2}   ║
╚════════╩══════╩═════════╝

Cars table
╔═══════╦══════════╦
║ carId ║ name     ║
╠═══════╬══════════╬
║   1   ║ honda    ║
║   2   ║ toyota   ║
║   3   ║ smart-car║
║   4   ║ bentley  ║
╚═══════╩══════════╩

1NF (First Normal Form)

Each table cell should contain a single value.
Each record needs to be unique.

2NF (Second Normal Form) Rules

Be in 1NF
Single Column Primary Key

这里重要的范式是第一个。

SQL 1999 年标准通过引入复合数据类型在某种程度上拓宽了视野。最好的看待它的方法是,如果数据在数据模型的上下文中是原子的,那么它就是原子的。否则,您必须考虑每个字符串都是非原子的(它由字符组成!)并将其拆分。

所以我要说的是,只要您不需要在数据库中获取单个数组项,或者——可怕的说法——执行与数组项的连接,使用数组就没有错。

现在这正是您想要做的,因此您绝对应该规范化数据模型。您的查询会更简单,也可能更快。