如果parent
s有child
ren,而child
ren有book
s他们读过,我怎么知道父母所有book
ren读过的所有child
s?
基本设置:
CREATE TABLE parent(
id SERIAL PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE child(
id SERIAL PRIMARY KEY,
parent INTEGER REFERENCES parent(id) NOT NULL,
name VARCHAR(50) NOT NULL
);
CREATE TABLE book(
id SERIAL PRIMARY KEY,
readBy INTEGER REFERENCES child(id) NOT NULL,
name VARCHAR(50) NOT NULL
);
插入一些数据:
INSERT INTO parent (name) VALUES
('Bob'),
('Mary');
INSERT INTO child (parent, name) VALUES
(1, 'Stu'), -- Bob has children Stu and Jane
(1, 'Jane'),
(2, 'Greg'), -- Mary has children Greg and Bella
(2, 'Bella');
INSERT INTO book (readBy, name) VALUES
(1, 'Crime & Punishment'), -- Stu has read C&P and Goodnight Moon
(1, 'Goodnight Moon'),
(2, 'The Singularity'), -- Jane has read The Singularity and 1fish2fish
(2, 'One Fish Two Fish'),
(3, 'Narnia'); -- Greg has read Narnia (Bella read nothing)
如何将包含“Bob”的查询作为参数,并让他的孩子阅读所有书籍?:
( 'Crime & Punishment', 'Goodnight Moon', 'The Singularity', 'One Fish Two Fish' )
同样的问题,除了涉及“玛丽”之外,只应给出“格雷格”读过的一本书,格雷格是她唯一一个读过任何东西的孩子:
( 'Narnia' )
提前感谢您的帮助!:)
免责声明:我肯定这个问题以前一定有人问过,但我找不到:(
最佳答案
你可以连锁
select book.name
from book
join child on book.readby=child.id
join parent on child.parent=parent.id
where parent.name='Bob';
或者如果您希望结果是数组/列表
这是不寻常的,通常结果是上面这样的行更有用,但您似乎需要一个单行结果。
select array_agg(book.name)
from book
join child on book.readby=child.id
join parent on child.parent=parent.id
where parent.name='Bob';
注意:结果可以按任何顺序显示。
关于postgresql - Postgres通过关系选择所有数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49456643/