需要帮助重构此查询

时间:2018-06-02 13:48:52

标签: sql postgresql

我得到了我的查询以返回我想要的内容,但感觉它本来可以做得更好。有人可以告诉我一个更好的方法来做这个查询问题,我也知道'活动'列是多余的,让我们去吧。

sql fiddle:http://sqlfiddle.com/#!17/18152/53

问题 - 请使用子查询,但我无法弄明白 - :“列出所有图书馆的顾客。如果他们签出了一本或多本图书,请将图书与顾客对应。”

SELECT p.name,
    (SELECT checked_in_date IS NULL AS active
     FROM transactions t
     WHERE p.id = t.patron_id AND b.isbn = t.isbn AND checked_in_date IS NULL),
  b.title
FROM patrons p
LEFT OUTER JOIN transactions t
ON p.id = t.patron_id  AND checked_in_date IS NULL
LEFT OUTER JOIN books b
ON b.isbn = t.isbn

期望的结果看起来像这样

 name    book_count(optional)  title
 ------------------------------------------
 Hermione Granger   0   (null)
 Terry Boot 1   Advanced Potion-Making
 Terry Boot 1   Fantastic Beasts and Where to Find Them
 Padma Patil    0   (null)
 Cho Chang  0   (null)
 Cedric Diggory 0   (null)

1 个答案:

答案 0 :(得分:1)

当我读到这个问题时,像这样的查询会做你想要的:

SELECT p.name,
       ARRAY_AGG(b.title)
FROM patrons p JOIN
     transactions t
     ON p.id = t.patron_id JOIN
     books b
     ON b.isbn = t.isbn
WHERE t.checked_in_date IS NULL
GROUP BY p.name