如何为 PostgreSQL 中的自链接记录设计最佳实践数据结构?

Posted

技术标签:

【中文标题】如何为 PostgreSQL 中的自链接记录设计最佳实践数据结构?【英文标题】:How to design a best practise data structure for self linked records in PostgreSQL? 【发布时间】:2018-07-25 06:54:10 【问题描述】:

在我的 PostgreSQL 数据库中,我需要定义以下数据结构。会有一个item的表,它有一个自增列item_id和其他item规格。输入新项目时,item_id 会加 1。这是针对父项目的。

还会有子项目具有相同的项目规格和它们的 unuqie item_id。多个子项可以与一个父项相关联。第一个孩子的 item_id 定义为 parent_item_id.1,第二个孩子定义为 parent_item_id.2,以此类推。

一个父项可以与多个子项相关联,从而形成“一对多”的关系。

pseudo Parent Item
item_id, item_name, attribute1, attribute2... attributeN
1, item_name1, attribute, attribute, ..., attributeN
2, item_name2, attribute, attribute, ..., attributeN
3, item_name3, attribute, attribute, ..., attributeN

Please note item_id for only the parent items needs auto-incrementing by 1.

pseudo Child Item
item_id, item_name, attribute1, attribute2... attributeN
1.1, item_name, attribute, attribute, ..., attributeN
1.2, item_name, attribute, attribute, ..., attributeN
1.3, item_name, attribute, attribute, ..., attributeN
2.1, item_name, attribute, attribute, ..., attributeN
2.2, item_name, attribute, attribute, ..., attributeN
3.1, item_name, attribute, attribute, ..., attributeN

结构化数据的最佳做法是什么?为父母和孩子制作两个单独的表,加上一个关系表是一个不错的选择吗?还是将父母和孩子放在一张桌子上?

【问题讨论】:

。 .我认为没有“最佳实践”。这取决于实体代表什么。 嗨。这是一个常见问题解答。请始终在谷歌上搜索您的问题/问题/目标的许多清晰、简洁和特定的版本/措辞,带和不带您的特定字符串/名称,并阅读许多答案。将您发现的相关关键字添加到搜索中。如果您没有找到答案,请发布,使用一种变体搜索您的标题和关键字作为标签。这也太宽泛了,你要的是一本书或一章。 What are the options for storing hierarchical data in a relational database?的可能重复 【参考方案1】:

我建议在同一个表中使用父子记录。作为规范化设计的一部分,使用带有 parent_item_id 的列。如果 Item 是父项,则 parent_item_id 将为 NULL,否则相应的 Item_id。

如何使用所有子记录跟踪父项? 使用递归 CTE 仅从单个 Item_id 获取所有记录。

【讨论】:

谢谢。父项的 item_id 自动递增 1,但子项不是。如何处理? 所有项目都将按 item_id 自动递增,无论是父项还是子项。【参考方案2】:

无需为 parent_item_id 创建自动增量引用。请参考以下示例。

CREATE TABLE item_mst(item_id BIGSERIAL, Item_name VARCHAR(100), parent_item_id BIGINT, is_active BOOLEAN, created_at TIMESTAMP)

For inserting Parent Item:
INSERT INTO item_mst(item_name, parent_item_id, is_active, created_at)
VALUES('Books',NULL, TRUE, NOW());

For inserting Child Items:
INSERT INTO item_mst(item_name, parent_item_id, is_active, created_at)
VALUES('Book_1',1, TRUE, NOW()), ('Book_2',1, TRUE, NOW()),('Book_3',1, TRUE, NOW());

select * from item_mst;

【讨论】:

以上是关于如何为 PostgreSQL 中的自链接记录设计最佳实践数据结构?的主要内容,如果未能解决你的问题,请参考以下文章

Postgresql:如何为postgres中的相同时间戳选择“媒体”列中的最大值?

如何为 Postgresql 中的所有数据库创建具有只读权限的用户?

如何为 postgresql 中的唯一(不包括顺序)JSONB 列创建约束

如何为 oracle 中的每个线程选择和阻止行?(PostgreSQL 有一个工作示例)

如何为postgresql中的每个用户返回具有最大值的类别?

如何为android中的所有视图使用相同的自定义字体?