查询双重排序

时间:2012-10-08 09:49:54

标签: mysql sql

我有一个项目表和他们来自哪个供应商:tabel items

Ttem ID - Item Title - Supplier - Date added

供应商可能提供多个项目,标题和供应商都不是唯一的。

我想展示最新添加的56件商品,从这56件商品中我想展示十大供应商

所以,我个人:

select * 
from items 
order by dateadded desc 
limit 56

供应商

select count(supplier) as howmany 
from items 
group by supplier 
order by howmany desc 
limit 10

我的问题是如何展示所选56个项目的前十名供应商

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

只需合并你的两个陈述并使用第一个陈述作为子选择:

select count(*) as howmany from (
    select * from items order by dateadded desc limit 56
) top_items group by supplier order by howmany desc limit 10

更新:您最初拥有count(supplier),这应该有效,但不是很清晰(看起来您正试图计算供应商的数量) 。我更改为count(*)以突出显示您正在计算每个供应商的行数(项目数)。

答案 1 :(得分:0)

这将使您获得最近56项的前10名供应商:

SELECT COUNT(supplier) AS howmany
FROM items

WHERE item_id IN (
    SELECT t2.item_id
    FROM items t2
    ORDER BY t2.dateadded DESC
    LIMIT 56
)

GROUP BY supplier
ORDER BY howmany DESC
LIMIT 10;