【问题标题】:FASTest > mysql get last distinct records return all columnsFASTest > mysql 获取最后不同的记录返回所有列
【发布时间】:2014-12-30 06:06:28
【问题描述】:
idx info    market  po  side    odd     unique_odd
10  927606  OU_OT   2.5 under   2.01    927606_OU_2.5_under
11  927606  OU_OT   2.5 under   2.02    927606_OU_2.5_under
12  927606  OU_OT   2.5 over    1.81    927606_OU_2.5_over
13  927776  OU_OT   3.5 under   1.67    927776_OU_3.5_under
14  927776  OU_OT   3.5 over    2.11    927776_OU_3.5_over
15  927776  OU_OT   3.5 over    2.31    927776_OU_3.5_over

odds_etc DATABASE 在这里。

我想像这样输出。

11  927606  OU_OT   2.5 under   2.02    927606_OU_2.5_under
12  927606  OU_OT   2.5 over    1.81    927606_OU_2.5_over
13  927776  OU_OT   3.5 under   1.67    927776_OU_3.5_under
15  927776  OU_OT   3.5 over    2.31    927776_OU_3.5_over

这意味着 unique_odd 和 MAX(idx) 不同 它可能低于 sql,但需要 7 秒。太长了,我要1~2秒。

SELECT T1.* FROM odds_etc T1
INNER JOIN (SELECT unique_odd,MAX(idx) as maxidx FROM odds_etc GROUP BY unique_odd) groupT2
ON T1.unique_odd = groupT2.unique_odd AND T1.idx = groupT2.maxidx 
WHERE info='$info'

【问题讨论】:

    标签: mysql performance max distinct


    【解决方案1】:

    使用odds_etc(unique_odd, idx) 上的索引,以下查询可能具有更好的性能:

    select oe.*
    from odds_etc oe
    where info = '$info' and
          not exists (select 1
                      from odds_etc oe2
                      where oe2.unique_odd = oe.unique_odd and
                            oe2.idx > oe.idx
                     );
    

    这会将查询表述为:“获取所有 unique_odd 没有更大值 idx 的行。”这是一种更复杂的说法:“为每个unique_odd 获取最大idx 的行。”但是这个版本可以利用上面的索引,应该会提高性能。

    您可能还希望在odds_etc(info, unique_odd, idx) 上建立索引。

    编辑:

    为了性能,你需要以下两个索引:

    create index idx_odds_etc_unique_odd_idx on odds_etc(unique_odd, idx);
    create index idx_odds_etc_info_unique_odd_idx on odds_etc(info, unique_odd, idx);
    

    【讨论】:

    • $sql = "SELECT * FROM odds_etc T1 where idx = ( SELECT MAX(idx) from odds_etc T2 WHERE T1.unique_odd = T2.unique_odd ) ";我也试过了,也需要 1 分钟。
    • @user3734604 。 . .那是两个索引?
    • @user3734604 。 . .您是否创建了答案中指定的两个索引?它们对性能很重要。
    猜你喜欢
    • 2019-05-26
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 1970-01-01
    相关资源
    最近更新 更多