首页 > 解决方案 > 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方法会更快,因为它对每个联赛都有一个查询,但我总是得到较旧的结果而不是最近创建的结果......

标签: sqlgroup-by

解决方案


您可以使用subquerywithlimit子句:

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
           );

推荐阅读