sql - SQL Group 按排序结果
问题描述
我的表如下所示:
----------------------------------------------------------
| ID | League | Reference | Created_at | Value |
----------------------------------------------------------
| 1 | Test | Exa | 2018-08-05 11:52:30 | 12.00 |
----------------------------------------------------------
| 2 | Test | Alch | 2018-08-05 12:52:30 | 9.12 |
----------------------------------------------------------
| 3 | Test | Chrom | 2018-08-05 12:50:30 | 6.00 |
----------------------------------------------------------
| 4 | Test | Chrom | 2018-08-05 10:50:30 | 2.00 |
----------------------------------------------------------
每 5 分钟我在表格上保存一个参考值
我想检索每个引用的值(按 . 排序的最新值created_at DESC
。目前在我的代码中,我只是遍历一个引用数组[exa, alch, ...]
并执行以下查询(对于每个联赛):
SELECT created_at, league, value, reference
FROM currency
WHERE league = ? AND reference = ?
ORDER BY created_at DESC
LIMIT 1
基本上我为每个联赛的每个引用执行该查询,导致执行大量查询,并导致我的服务器上的响应时间很长......
预期的结果应该是created_at DESC
,从 X 联赛中收集每个参考值,但只收集最新插入的值created_at
( )
我尝试使用group_by
完全没有成功,因为我只会得到表的第一个结果(旧的):
SELECT created_at, league, value, reference
FROM currency
WHERE league = ? AND reference IN ('exa', 'alch', ...)
GROUP BY created_at DESC
我认为这种group_by
方法会更快,因为它对每个联赛都有一个查询,但我总是得到较旧的结果而不是最近创建的结果......
解决方案
您可以使用subquery
withlimit
子句:
select c.*
from currency c
where id = (select c1.id
from currency c1
where c1.league = c.league and
c1.Reference = c.Reference -- might be you need this also
order by c1.created_at desc
limit 1
);
推荐阅读
- html - 用透视图渲染 HTML 元素?
- ios - 当超类也是 Codable 时,如何在子类中使用 CodingKeys?
- jsdoc - 如何使用 jsdoc 描述导出默认值 ({ Label, initialValue, })=>{ ... }
- vba - 更新子表单上的记录
- gnuplot - 如何仅对 gnuplot 中的 1 个数据源使用设置偏移量?
- flutter - 颤振更新圆形图表持有带有redux商店的标签
- c# - 将数据类型 nvarchar 转换为数字的 ASP.NET 错误
- sqlite - 将 .csv 插入 sqllite3 并出现“预期 5 列但发现 1”问题
- reactjs - React fetch failed: "TypeError: Failed to fetch" 即使 API 返回数据
- google-drive-api - 如何通过 API 识别与 Google 驱动器文件关联的脚本 ID