Postgres通过关系选择所有数据

时间:2018-03-23 18:55:05

标签: postgresql select

如果<asp:DropDownList runat="server" ID="ddl" AutoPostBack="true" />parent个,而childchild个已阅读,我怎么知道所有book个已阅读由父母的所有book仁?

基本设置:

child

插入一些数据:

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

如何制定一个{“1}}查询,将”Bob“作为参数并获取他孩子阅读的所有书籍?:

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)

同样的查询,除了涉及“玛丽”之外,只应该只给一本书读“Greg”,这是她唯一读过任何东西的孩子:

SELECT

提前感谢您的帮助! :)

免责声明:我确定此问题必须先问过,但我找不到:(

1 个答案:

答案 0 :(得分:0)

您可以链接join s

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

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