SQL查询所需的建议

时间:2013-04-27 13:35:01

标签: sql

我正在学习几周的考试,并且遇到了一个我仍然无法弄清楚的SQL查询问题。我想知道是否有人可以建议我。

关系数据库:

Books(**ISBN**, Title, Genre, Price, Publisher, PublicationYear)

Author(**AuthorNum**, Name)

Write(**ISBN**, AuthorNum)

问题:找出每个出版商最昂贵的书籍,以及作者姓名,按书名字母顺序排列。

我尝试了很多东西,其中一个是我认为最接近解决方案的东西,但它不正确:

SELECT Title, Name
FROM Author AS a, Books AS b, Write AS w
WHERE a.AuthorNum = w.AuthorNum AND b.ISBN = w.ISBN
GROUP BY Publisher
HAVING MAX(Price)
ORDER BY Title

3 个答案:

答案 0 :(得分:4)

内联视图通常在各种数据库上表现良好。不要过早地优化。

您可以获得每位发布商的最高价格:

1

    select publisher, max(price) as MaxPublisherPrice
    from books
    group by publisher

您可以通过加入上述语句返回的集合,找出每个发布商的哪些图书的价格等于MaxPublisherPrice:

2

    select books.title, P.MaxPublisherPrice as bookprice
    from books
    inner join
    (
      select publisher, max(price) as MaxPublisherPrice
      from books
      group by publisher
    ) as P
    on books.publisher = P.publisher
    and books.price = P.maxpublisherprice

然后您可以输入作者姓名:

3

    select books.title, P.MaxPublisherPrice as bookprice, author.name
    from books
    inner join
    (
      select publisher, max(price) as MaxPublisherPrice
      from books
      group by publisher
    ) as P
    on books.publisher = P.publisher
    and books.price = P.maxpublisherprice
    inner join write
    on write.isbn = books.isbn
    inner join author 
    on write.authornum = author.authornum
    order by books.title

答案 1 :(得分:1)

我就是这样做的:

SELECT  b.Title, b.Name, b.Publisher, a.Author

FROM        Books  b
LEFT JOIN   Write  w    ON w.ISBN       = b.ISBN
INNER JOIN  Author a    ON a.AuthorNum  = w.AuthorNum  

WHERE   b.Price = (SELECT MAX(bb.Price) FROM Books bb
                   WHERE b.Publisher = bb.Publisher)

ORDER BY Title
;

请注意一些更好的观点:

  1. 仅使用标准SQL语法,不使用特定于供应商的语法,也不使用已弃用的语法
  2. 可以容纳多本图书可能具有来自一个发布商的最高价格
  3. 适应书籍可能有多个作者的可能性
  4. 适应书籍可能没有任何已知作者
  5. 的可能性
  6. 避免不必要地使用GROUP BY,研究表明这可能比连接或子查询慢。

答案 2 :(得分:0)

您需要对图书作者的出版商,标题和名称进行分组。不仅是出版商。

分组允许分割(或分解)行。 (因为您订购desc价格,最高价格是无用的)

我不会在这里写查询,因为我不会做你的作业:D:D