|
我有以下结构:. }4 M9 ?. k' g. B
CREATE TABLE author id integer ,name varchar(255));CREATE TABLE book id integer ,author_id integer ,title varchar(255) ,rating integer);我希望每个作者都能读到最后一本书:5 a! J& X. l a
SELECT book.id,author.id,author.name,book.title as last_bookFROM authorJOIN book book ON book.author_id = author.idGROUP BY author.idORDER BY book.id ASC显然,你可以在那里mysql执行此操作:在MySQL连接两个表,只从第二个表返回一行。
. l |. z9 x. u M但是postgres给出这个错误:
n. i' l' f3 s3 z& ?错误:“ book.id必须出现列GROUP BY用于子句或聚合函数:SELECT
2 o% `6 R/ X4 b1 c$ r/ ?2 vbook.id,author.id,author.name,book.title为last_book FROM author JOIN book( y# I6 [1 w, D' B/ N2 ]' J0 w
book on book.author_id = author.id GROUP BY author.id ORDER BY book.id ASC& s& f/ b/ r9 {: a0 v3 x# w
这是因为:
" @1 ?9 `+ a, M+ q6 p. ?7 d如果存在GROUP BY,则SELECT未分组列(聚合函数除外)不能引用列表表达式,因为未分组列将返回多个可能值。- n4 ]/ U) g! g
我如何指定postgres:“仅joined_table.id在连接表中按顺序给我最后一行?
9 ?: O- A, _$ e; }8 D9 ~+ D1 O1 n编辑:使用此数据: k8 A* V' U) n z0 V1 o
INSERT INTO author (id,name) VALUES (1,'Bob(二),David(3),John');INSERT INTO book (id,author_id,title,rating) VALUES 1、1、1、1st book from bob五、nd book from bob六、rd book from bob七、st book from David(、nd book from David',6);我应该看到:6 [. D) j: X/ b8 n
book_id author_id name last_book3 3 1 "Bob" "3rd book from bob"5 2 "David" "2nd book from David"
% Q r, b/ B# P H1 k 解决方案: ' c- ^, ^ v" A9 g( I2 J9 X
select distinct on (author.id) book.id,author.id,author.name,book.title as last_bookfrom author inner join book on book.author_id = author.idorder by author.id,book.id desc查看 distinct on. G. r- N: x/ {4 @
SELECT DISTINCT ON(expression [,…])每组行的第一行只保留给定表达式。ORDER: G6 X. |+ S Q$ A# R% k. z5 n$ ^
BY解释相同的规则DISTINCT ON表达式(请参见上面)。请注意,除非使用。ORDER
. n+ w* ]) |) ?9 M& \ m& h# d9 aBY确保所需的行先出现,否则每一集的第一行都是不可预测的。, H, H% Y' d; X( f
内容独特,有必要在其中添加独特列order by。如果不是你想要的顺序,你需要包装查询并重新排序
8 b4 V0 D" M1 R) C+ x& Cselect *from select distinct on (author.id) book.id,author.id,author.name,book.title as last_book from author inner join book on book.author_id = author.id order by author.id,book.id desc) authors_with_first_bookorder by authors_with_first_book.name另一种解决方案是使用Lennart答案中的窗口函数。另一个很常见的是# y5 @) \" G: J7 A5 _0 i' j4 w
select book.id,author.id,author.name,book.title as last_bookfrom book inner join ( select author.id as author_id,max(book.id) as book_id from author inner join book on author.id = book.author_id group by author.id ) s on s.book_id = book.id inner join author on book.author_id = author.id |
|