Postgres查询只有一位作者的归还书籍

时间:2019-05-25 17:08:12

标签: sql postgresql

我正在尝试查询返回书名,书摘和作者姓名的书籍,其中只有一位作者按书号排序。一本书可以有很多作者,而一位作家可以写很多书,所以这是多对多的关系,但是我在做错事或忘记了事。

我的表是:

book_tb(id, title, summary);
author_tb(id, name);
book_author_tb(id, book_id, author_id);

我已经尝试过:

SELECT b.title, b.summary, a.name 
FROM book_tb b
INNER JOIN book_author_tb ba ON b.id = ba.book_id
INNER JOIN author_tb a ON ba.author_id = a.id
GROUP BY b.title, b.summary, a.name, b.id
HAVING count(ba.author_id) = 1
ORDER BY b.id;

3 个答案:

答案 0 :(得分:4)

一种方法是:

SELECT b.title, b.summary, a.name 
FROM book_author_tb ba 
INNER JOIN book_tb b ON b.id = ba.book_id
INNER JOIN author_tb a ON a.id = ba.author_id
WHERE (
  SELECT COUNT(*) 
  FROM book_author_tb
  WHERE book_id = b.id
) = 1
ORDER BY b.id

此:

SELECT COUNT(*) FROM book_author_tb WHERE book_id = b.id

确保返回的书籍只有1位作者。
另一种方法(可能更有效):

SELECT b.title, b.summary, a.name 
FROM (
  SELECT book_id, MAX(author_id) author_id 
  FROM book_author_tb
  GROUP BY book_id
  HAVING COUNT(*) = 1
) ba 
INNER JOIN book_tb b ON b.id = ba.book_id
INNER JOIN author_tb a ON a.id = ba.author_id
ORDER BY b.id

答案 1 :(得分:2)

我会通过聚合来做到这一点:

SELECT b.title, b.summary, MAX(a.name) as name
FROM book_author_tb ba INNER JOIN
     book_tb b
     ON b.id = ba.book_id INNER JOIN
     author_tb a
     ON a.id = ba.author_id
GROUP BY b.title, b.summary
HAVING COUNT(*) = 1;

此版本计算每本书的作者人数(假设没有重复,这是合理的)。

您的版本也被作者汇总。在这种情况下,count()只会是“ 1”。

答案 2 :(得分:1)

您应该在其他子选择中计算所需过滤器的作者数。因此,从现在开始,您可以在WHERE语句中使用它。

     SELECT b.title, b.summary, a.name FROM book_tb b
     JOIN book_author_tb ba ON b.id = ba.book_id
     JOIN author_tb a ON ba.author_id = a.author_id
     GROUP BY b.title, b.summary, a.name, b.id
     WHERE (SELECT count(ba.author_id) 
                FROM book_author_tb
                WHERE book_id = b.id) = 1
     ORDER BY b.id;