我有一个跟踪兄弟姐妹的应用程序。有一个"会员"表。这就是现在。会员可以是兄弟姐妹"彼此我想以某种方式跟踪"会员"的不同成员之间的关系。表。我尝试这样做:
CREATE TABLE members (
id SERIAL PRIMARY KEY,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL
);
CREATE TABLE siblings (
member_one_id INTEGER REFERENCES members (id),
member_two_id INTEGER REFERENCES members (id),
PRIMARY KEY (member_one_id, member_two_id)
);
但我不知道如何查询这个结构。我试过这个
SELECT * FROM members
INNER JOIN siblings
ON members.id = siblings.member_one_id OR members.id = siblings.member_two_id
INNER JOIN members
ON members.id = siblings.member_one_id OR members.id = sibling.member_two_id;
我一直收到错误:
ERROR: table name "members" specified more than once
有没有办法存储这种类型的关系并有效地查询它?对于像这样的更复杂的结构,我的SQL知识变得越来越薄。谢谢!
答案 0 :(得分:1)
使用这样的表别名:
SELECT * FROM members one
INNER JOIN siblings
ON one.id = siblings.member_one_id OR one.id = siblings.member_two_id
INNER JOIN members two
ON two.id = siblings.member_one_id OR two.id = sibling.member_two_id
答案 1 :(得分:0)
表结构看起来不错。您可以使用CTE遍历关系(https://www.postgresql.org/docs/9.1/static/queries-with.html)