mysql - 如何从表中获得前三名

标签 mysql sql

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

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

最佳答案

如果您只需要三个产品(不管平局如何),则使用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

选择之前。两者都会保存表格,以便您稍后查询。第二个创建一个临时表,该表将在 session 结束时消失。

关于mysql - 如何从表中获得前三名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50398297/

相关文章:

sql - 查询语句在 oracle 上执行时间很长

sql - T-SQL 到 "Merge"两行,或 "Rekey"所有 FK 关系

mysql - 将 sql 文件复制到 Raspberry Pi 上的不同数据库中

PHP - 进阶 MYSQL 同时

mysql - 查找和替换 ## 之间的文本

SQL XML 命名空间

sql - 如何强制提交正在运行的 t-sql 查询(完成一半)?

php - 在 PHP 中使用 UPDATE 语句时的 MySQL 字符问题

mysql - 表插入不存在的值

mysql - 使用 WHERE 时如何将 “zero”/“0” 结果包含在 COUNT 中?