基于SUM对MySQL查询进行排序

时间:2014-12-07 00:20:11

标签: mysql select

我很难获得正确的查询: 有两个表:articlesorders

我想从所有文章中获取一个列表,但按照订购时间排序。 (不仅订购商品的次数,还包括金额)

ordersid, article_id, amount

articlesid, description

示例:

articles

1, apple
2, orange
3, lime

orders

1, 1, 5
2, 3, 1
3, 3, 2
4, 2, 1

输出应为:

1, apple,  5
3, lime,   3
2, orange, 1

2 个答案:

答案 0 :(得分:1)

这是一个基本的joingroup by查询,是SQL语言的两个基础。如果要有效地使用数据库,应该学习该语言。

select a.`key`, count(o.id) as cnt, sum(amount)
from articles a left join
     orders o 
     on o.article_key = a.`key`
group by a.`key`
order by cnt desc;

答案 1 :(得分:0)

select a.key, a.description, sum(amount) as sum_amount
from articles a
left join orders o on o.article_key = a.key
group by a.key, a.description
order by sum_amount desc