我很难获得正确的查询:
有两个表:articles
和orders
我想从所有文章中获取一个列表,但按照订购时间排序。 (不仅订购商品的次数,还包括金额)
orders
:id, article_id, amount
articles
:id, 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
答案 0 :(得分:1)
这是一个基本的join
和group 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