SQL查询中的不同关键字用法

时间:2013-02-08 09:50:44

标签: sql database

我有一张名为manuscripts的表

BOOKID  AUTHORID BOOKNAME       GENRE   NOOFCOPIES  AMOUNT
B105    A102     Diagnosis      Journal 500         10000
B102    A102     The Essence... Fiction 110         11000
B106    A102     Clinical Sci.  Educat. 125         18750
B104    A103     Mind Games     Fiction 200         20000
B100    A102     Sublime        Fiction 100         10000
B101    A105     C Programming  Educati 125         18750
B103    A101     Scribe         Journal 500         10000
B107    A101     Clinical Chem. Educat. 125         54646
B108    A103     Clinical Chem. Educat. 125         54646  

如何获得已支付最高金额的AuthorIds?如果我写

select distinct a.AuthorId,m.amount 
from Author a,manuscripts m 
where m.amount in (select max(amount) 
                   from manuscripts m 
                   where a.AuthorId=m.AuthorId)

然后我能够得到正确的输出,但是如果我添加bookname那么它将无法正确显示..

2 个答案:

答案 0 :(得分:3)

由于您没有提到您正在使用的RDBMS,下面的查询几乎可以使用RDBS,(并非所有

SELECT  a.*
FROM    tablename a
        INNER JOIN
        (
            SELECT  AuthorID, MAX(Amount) max_amount
            FROM    tableName
            GROUP   BY AuthorID
        ) b ON  a.AuthorID = b.AuthorID AND
                a.Amount = b.max_amount

要获得更快的效果,请在INDEX

上添加复合列AuthorID, Amount

答案 1 :(得分:0)

这将显示价格最高的每一行:

SELECT m.*
FROM amanuscripts m
WHERE m.amount = (select MAX(amount) FROM manuscripts)

这将显示每个作者的价格最高的每一行:

SELECT m.*
FROM manuscripts m
WHERE (m.authorid, m.amount) IN (select authorid, MAX(amount)
                                 FROM manuscripts
                                 GROUP BY authorid)

(根据上表的结构,不需要使用Manuscripts表连接Author表)