我有以下模式:
CREATE TABLE author (
id integer
, name varchar(255)
);
CREATE TABLE book (
id integer
, author_id integer
, title varchar(255)
, rating integer
);
我希望每个作者都能写出最后一本书:
SELECT book.id, author.id, author.name, book.title as last_book
FROM author
JOIN book book ON book.author_id = author.id
GROUP BY author.id
ORDER BY book.id ASC
显然你可以在 mysql: 在 MySQL 中联接两个表,只从第二个表返回一行中做到这一点。
但是 postgres 给出了这个错误:
ERROR: 列“ book.id”必须出现在 GROUP BY 子句中或者使用 在聚合函数中: SELECT book.id、 author.id、 author.name, Title as last _ book FROM author JOIN book book ON book.author _ id = Id GROUP BY auth.id ORDBY book.id ASC
当 GROUPBY 存在时,它对 SELECT 列表无效 表达式引用聚合以外的未分组列 函数,因为返回的值可能不止一个 用于未分组的列。
如何指定 postgres: “当按 joined_table.id
排序时,只给我联接表中的最后一行?”
编辑: 根据这些数据:
INSERT INTO author (id, name) VALUES
(1, 'Bob')
, (2, 'David')
, (3, 'John');
INSERT INTO book (id, author_id, title, rating) VALUES
(1, 1, '1st book from bob', 5)
, (2, 1, '2nd book from bob', 6)
, (3, 1, '3rd book from bob', 7)
, (4, 2, '1st book from David', 6)
, (5, 2, '2nd book from David', 6);
我应该看看:
book_id author_id name last_book
3 1 "Bob" "3rd book from bob"
5 2 "David" "2nd book from David"