如何从表中获得前三名

时间:2018-05-17 18:32:39

标签: mysql sql

我希望在表格中打印最畅销的三大产品。所以我做了表

select articel_id, article_count
from
(select articel_id, count( articel_id) as article_count
from sales_records_row
group by  articel_id
order by count(articel_id) DESC 
) as overview

哪个给出了

article_id      article_count
 1                30
 2                12
 4                8
 5                8
 8                8
 etc              etc

但我似乎无法拨打我的新概述表"因为它不是原始数据库的一部分。我想使用article_id查找文章名称,然后获取一个包含列

的表
article_name      article_count

我甚至可以使用我的第一个代码,还是有更合适的方式来解决这个问题?

**编辑 我现在想出了这个解决方案。这和有一个JOIN有什么区别?

select articles.name as 'Product Name', article_count
from
(select articel_id, count( articel_id) as article_count
from sales_records_row
group by  articel_id
order by count(articel_id) DESC limit 3
) as overview, articles
where articles.articel_id = overview.articel_id

3 个答案:

答案 0 :(得分:2)

如果您只想要三种产品(无论关系如何),请使用limit

select articel_id, count( articel_id) as article_count
from sales_records_row
group by  articel_id
order by count(articel_id) DESC 
limit 3;

如果要将结果存储在表格中,请使用:

create table <table name> as

create temporary table <table name> as
select之前

。要么保存表,以便稍后查询。第二个创建一个临时表,当会话结束时它将消失。

答案 1 :(得分:0)

执行JOINS

select o.articel_id, t.article_name, o.article_count  
from table t
inner join (select articel_id, count(articel_id) as article_count
            from sales_records_row
            group by  articel_id
            order by count(articel_id) DESC
            LIMIT 3) o on o.articel_id = t.articel_id;

答案 2 :(得分:0)

SELECT articel_id, article_count, row_num
FROM(
   SELECT articel_id, count(articel_id) as article_count, @r:=@r+1 row_num
   FROM sales_records_row, (SELECT @r:=0) t
   GROUP BY articel_id ORDER BY article_count DESC
) a WHERE a.row_num BETWEEN 1 AND 3;

请试试这个