【发布时间】:2018-03-23 18:55:04
【问题描述】:
如果parents 有children,children 有books 他们读过,我怎么知道父母的所有children 读过的所有books ?
基本设置:
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”作为参数的SELECT 查询并获取他的孩子阅读的所有书籍?:
( 'Crime & Punishment', 'Goodnight Moon', 'The Singularity', 'One Fish Two Fish' )
相同的查询,除了涉及“玛丽”,应该只给出“格雷格”读过的一本书,她是她唯一读过任何东西的孩子:
( 'Narnia' )
提前感谢您的帮助! :)
免责声明:我确信这个问题之前一定有人问过,但我找不到它:(
【问题讨论】:
-
我的 postgres 从 1 开始连载。
-
你说得对,我的也是——我会编辑修复
标签: postgresql select