英文:
Postgres Database - One object links to one or mare objects from Same table
问题 {#heading}
这是一个情景:
我有一个对象,比如说一只猫。例如,当我向数据库插入猫4的详细信息时,我可以将猫1、2和3添加到猫4中。在网页上,当我点击猫4的链接时,我需要打开一个新页面,显示猫4的详细信息以及猫1、2和3的详细信息。
我不关心前端实现,我只想知道如何在数据库中设计这个功能。我认为这与继承无关,因为我们处理的是同一类型的对象,即猫。
我可以通过在猫表中创建一个包含子猫ID的数组字段来简化它,但我不确定这是否是最佳解决方案。或者在Postgres数据库中实现这一功能可能有更好的方法。 英文:
This is a senario:
I have got a object let's say a cat. For example when I insert the cat 4 details to database, I can add cats to cat 4, lets say cat 1, 2 and 3.In web page, when I click on cat 4 link, I need to open new page with details of cat 4 plus cat 1, 2 and 3.
I am not wondering about the frontend implementation, I only want to know how can this be designed in database. I do not think this is related to inheritance since we are dealing with same type of object which is a cat.
I can make it simple by creating a array field in cat table that contains children's ids, but I am not sure if this is the best solution. Or It could be better way to implement this in Postgres database.
答案1 {#1}
得分: 1
CREATE TABLE Cat (
cat_id SERIAL PRIMARY KEY,
name VARCHAR(255),
-- 其他猫的详细信息...
);
CREATE TABLE CatHierarchy (
parent_cat_id INT REFERENCES Cat(cat_id),
child_cat_id INT REFERENCES Cat(cat_id),
PRIMARY KEY (parent_cat_id, child_cat_id)
);
英文:
you can try this
-- Cat Table
CREATE TABLE Cat (
cat_id SERIAL PRIMARY KEY,
name VARCHAR(255),
-- Other cat details...
);
`-- CatHierarchy Table
CREATE TABLE CatHierarchy (
parent_cat_id INT REFERENCES Cat(cat_id),
child_cat_id INT REFERENCES Cat(cat_id),
PRIMARY KEY (parent_cat_id, child_cat_id)
);
`
答案2 {#2}
得分: 0
不要使用数组,它们无法维护数据完整性。
可以使用类似这样的方法:
创建表 animals(
id_animal INT 主键 由默认生成 AS IDENTITY
, id_animal_type INT -- 外键指向动物类型,比如猫、狗等
, id_mom INT 引用 animals(id_animal)
, id_dad INT 引用 animals(id_animal)
, gender CHAR(1) 检查 ( gender 在('m','f') )
, name TEXT
-- 等等
);
英文:
Don't use arrays for this, they can't maintain data integrity.
Something like this could work:
CREATE TABLE animals(
id_animal INT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY
, id_animal_type INT -- foreign key to animal types, like cat, dog, etc
, id_mom INT REFERENCES animals(id_animal)
, id_dad INT REFERENCES animals(id_animal)
, gender CHAR(1) CHECK ( gender IN('m','f') )
, name TEXT
-- etc
);