SQL简单查询问题

时间:2014-01-27 13:09:41

标签: sql sql-server

我有一个简单的SQL问题。

我有3张桌子

Books
--------------------
Book_ID(pk) | Title | Price
--------------------

Clients
---------------------
Client_ID(pk) | Name |

CardsOfReaders
---------------------
Book_ID(pk,fk)| Client_ID(pk, fk)

所以问题是:如何显示以最高价格借阅图书的读者姓名(以及要显示的列价)

提前致谢!

3 个答案:

答案 0 :(得分:7)

select top 1 c.name, b.price
from books b
inner join cardsofcreaders cr on cr.book_id = b.book_id
inner join clients c on c.client_id = cr.client_id
order by b.price desc

答案 1 :(得分:4)

根据您的表结构,对您的问题稍微不同一点,请注意,多个客户可以以最昂贵的价格借阅该书。要找到所有这些客户:

SELECT c.Name, b.Price
FROM 
  (
    SELECT TOP 1 Book_ID, Price
    FROM BOOKS
    ORDER BY Price desc
  ) b
  INNER JOIN CardsOfReaders car
  on b.BOOK_ID = car.BOOK_ID
  INNER JOIN Clients c
  ON car.ClientID = c.Client_ID;

答案 2 :(得分:2)

或者另一种变化,因为在现实生活中许多书可能具有相同的,最高的价格。

SELECT C.name, B.Price --,B.Title /*In case there are several books*/
FROM (SELECT MAX(Price) MPrice
   FROM BOOKS) mx
JOIN BOOKS B ON B.Price = mx.MPrice
JOIN CardsOfReaders crd ON crd.BOOK_ID = B.BOOK_ID
JOIN Clients C on C.ClientID = crd.ClientID