我有一张足球赔率表,如下所示:
fixture_id | H_odds | D_odds | A_odds | ev_tstamp | 更新 |
---|---|---|---|---|---|
120000 | 1.40 | 1.50 | 1.60 | 132000 | 12 |
120000 | 1.20 | 1.20 | 1.20 | 132000 | 11 |
120000 | 1.20 | 1.20 | 1.20 | 132000 | 10 |
120000 | 1.10 | 1.20 | 1.20 | 132000 | 9 |
180000 | 1.20 | 1.30 | 1.60 | 132000 | 12 |
180000 | 1.10 | 1.20 | 1.20 | 132000 | 11 |
180000 | 1.50 | 1.80 | 1.50 | 132000 | 10 |
我想从更新值为 MIN 和 MAX 的赔率之间的差值以及更新值为 MAX 的赔率本身获得一组 ids 中的每个 fixture_id。
所以基于这个例子,结果应该是:
fixture_id | H_odds | D_odds | A_odds | ev_tstamp | 更新 | dif_h | dif_d | dif_a |
---|---|---|---|---|---|---|---|---|
120000 | 1.40 | 1.50 | 1.60 | 132000 | 12 | 0.3 | 0.3 | 0.4 |
180000 | 1.20 | 1.30 | 1.60 | 132000 | 12 | -0.3 | -0.5 | 0.1 |
我能想到的唯一方法是这样的:
select t.H_odds from avg_odds t where
t.updated = (select min(t2.updated) from avg_odds t2 where
t2.fixture_id = t.fixture_id and t2.updated= t.updated )
-
t.H_odds from avg_odds t where
t.updated = (select max(t2.updated) from avg_odds t2 where
t2.fixture_id = t.fixture_id and t2.updated= t.updated ) as dif_h
where fixture_id in ($list_of_ids)
有更简单的解决方案吗?
答案 0 :(得分:1)
您可以通过加入表格本身来做到这一点:
select
t_max.*,
(t_max.H_odds - t_min.H_odds) as dif_h,
(t_max.D_odds - t_min.D_odds) as dif_d,
(t_max.A_odds - t_min.A_odds) as dif_a
from
(
select
fixture_id,
min(updated) min_updated,
max(updated) max_updated
from
test
group by
fixture_id
) as t1
join test as t_min on (t_min.fixture_id = t1.fixture_id and t_min.updated = t1.min_updated)
join test as t_max on (t_max.fixture_id = t1.fixture_id and t_max.updated = t1.max_updated)
在 MySQL >= 8 中可能有一个使用窗口函数的解决方案,但我不太确定,因为聚合函数本身无法获取您需要的字段,它们只是由聚合标识(即 { {1}} 和 min
) + fixture_id。
你需要这样的东西:
max
这会为所有分组的“fixture_id”获得最大更新(但你不想要“min(updated)”,你想要“H_odds”等具有“min(updated) AND fixture_id = "fixture_id of max(updated ) 具有相同的 fixture_id') - 如果我错了,请纠正我,不存在。 但是由于您不使用 MySql >= 8 无论如何这不是一个选项。
并且请获取唯一 ID :)
你需要索引你的表:
SELECT
MIN(updated) over (partition by fixture_id)
...
如果你不这样做,你的文件系统上就会有临时表 -(非常非常慢)
工作example。
更新:一个相当不愉快的 MySQL >= 8 example(使用文件排序 - 请勿使用)。