【问题标题】:Postgres select all data via relationPostgres 通过关系选择所有数据
【发布时间】: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


【解决方案1】:

你可以链接joins

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';

注意:结果可以按任意顺序显示。

【讨论】:

  • 这很好用!我不需要数组格式(我想我用来演示我想要的结果的语法让你感到困惑)但是了解array_agg 也很有用
猜你喜欢
  • 2010-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多