双连接中的SQL最大条件

时间:2011-12-15 15:12:24

标签: sql join max

所以我们有3个相关的表格:

  • book,其中包含属性title, numberofpages
  • personlast nameid
  • writesauthor(= person.id)和book(= book.title

因此,我们希望找到作为作者的每个人的姓氏以及具有最高页码的书籍的页数。

我们尝试了这个:

SELECT lastname, numberofpages
FROM book, person, writes 
WHERE person.id=writes.author AND book.title=writes.book

返回:

author A  number of pages of his book 1
author A  number of pages of his book 2
author B  number of pages of his book 1  

依旧......

我们怎样才能使每个作者只给出一行,其中只包含最多编号的书页数?我们使用max(numberofpages)尝试了各种子选择,但无法使其工作。

3 个答案:

答案 0 :(得分:2)

您需要按作者分组,然后选择max

SELECT person.lastname, max(book.numberofpages)
FROM book, person, writes 
WHERE person.id=writes.author AND book.title=writes.book
GROUP BY person.lastname, person.id

您还应该考虑使用现代连接语法,并保留有关具有不同ID但姓氏相同的作者的信息:

SELECT person.lastname, max(book.numberofpages)
FROM book
JOIN writes ON book.title=writes.book
JOIN person ON person.id=writes.author
GROUP BY person.id, person.lastname

答案 1 :(得分:2)

您必须使用group by这样的句子:

select p.lastname, max(w.numberofpages)
from writes w
inner join person p on p.id = w.author
inner join books b on b.title = w.book
group by p.lastname, p.id

答案 2 :(得分:0)

您必须使用GROUP BY

SELECT person.lastname, max(writes.numberofpages)
FROM book, person, writes  
WHERE person.id=writes.author AND book.title=writes.book 
GROUP BY person.lastname, person.id