首页 > 解决方案 > 如何从表中获得前三名

问题描述

我想在表格中打印前 3 名最畅销的产品。所以我做了一张桌子

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

标签: mysqlsql

解决方案


如果您只想要三种产品(无论领带如何),请使用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。两者都将保存表,以便您稍后查询。第二个创建一个临时表,该表将在会话结束时消失。


推荐阅读