mysql - 如何从表中获得前三名
问题描述
我想在表格中打印前 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
解决方案
如果您只想要三种产品(无论领带如何),请使用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
。两者都将保存表,以便您稍后查询。第二个创建一个临时表,该表将在会话结束时消失。
推荐阅读
- arrays - 快速解码:预期解码数组
但找到了一本字典 - python-3.x - 当特定文本文件的模式匹配时,正则表达式返回单行
- r - 如何在 Blastula 电子邮件正文中合并 html 文件
- ios - Swift——子类视图控制器不继承超类属性
- python - 如何将多个文件附加到电子邮件?
- jquery - 内容安全政策 - 拒绝从谷歌分析加载脚本 - CSP 规则正确
- java - SpringBatch 从网络数据库中读取
- database - Kafka Connect 流和 Postgresql DataFileRead 性能缓慢
- javascript - JavaScript 输入字段在加载时获取旧值
- java - 多个信标消费者和信标未使用 AltBeacon 检测