淘客熙熙

主题:【求助】一个MySQL query的问题 -- 阿国

共:💬6 🌺2 新:
分页树展主题 · 全看首页 上页
/ 1
下页 末页
  • 家园 【求助】一个MySQL query的问题

    我想把table_one里log_type_id是81和82的timestamp的差拿出来(timestamp 82 - timestamp 81, 前提是abclog_id是一样的), 而abclog_id是从另外table_two提出来, 大概就是(select abclog_id from table_two where ....).

    有什么办法可以一个QUERY里做到吗? 如果我还想把table_two 里的uid 也提出来呢.

    例如这就是我想要的结果(当然, 真正的结果可能是很多页的):

    |-----+

    |time |

    |-----+

    |2479 |

    |-----+

    或是

    ------------+

    | uid | time|

    +-----------+

    | 2479| 2479|

    -------------

    table_one

    +-----------+-----------+---------+------------+

    | abclog_id |log_type_id| id | timestamp |

    +-----------+-----------+---------+------------+

    | 247927204 | 81 | 10904 | 3680400000 |<--81

    | 247927204 | 82 | 11160 | 3680402479 |<--82

    | 247927278 | 83 | 11175 | 3680972384 |

    | 247927284 | 84 | 11189 | 3681492382 |

    | 247927289 | 85 | 11204 | 3682317381 |

    -------------------------------------------------

    table_two

    +-----------+-------------+

    | uid | abclog_id | others|

    +-----------+-------------+

    | 2479| 247927204 | xxxxx |

    ---------------------------

    • 家园 SQL Server 下我会这么做

      --assume timestamp is integer

      select abclog_id, sum(case when log_typeid = 82 then timestamp else 0 end) - sum(case when log_typeid = 81 then timestamp else 0 end) as [time]

      from table_one

      where abclog_id = 247927204 and log_type_id in (81, 82)

      group by abclog_id

      MySQL 不熟,估计原理差不多吧,就是巧用group by而已。

    • 家园 可以做到

      可以,做三个virtual table,你没给完整的table schema,所以只大致提一下用法

      select a3.uid,TIMESTAMPDIFF(second,a1.timestamp,a2.timestamp)... from

      (select abclog_id,timestamp, ... from table_one where log_type_id=81) a1,

      (select abclog_id,timestamp, ... from table_one where log_type_id=82) a2,

      (select abclog_id,uid,... from table_two where

      ...) a3

      where a1.abclog_id=a2.abclog_id

      and a1.abclog_id=a3.abclog_id

      • 家园 可以用, 不过效率是个问题

        40957 rows in set (41 min 41.91 sec)

        得想办法优化了, 再看看, 谢谢.

        • 家园 优化就要具体问题具体分析了

          你的table的总行数有多少? 几个搜索的关键column有没有做index,跑一下explain上面的query,看看是不是所有的index都充分利用了

          • 家园 想到一个方法, 快了N倍

            select count(a1.abclog_id) from abclog_entries_20080301 a1 where a1.log_type_id=86 and a1.abclog_id in (select a2.abclog_id from abclog_entries_20080301 a2 where a2.log_type_id=89 and a2.abclog_id in (select a3.abclog_id from abclogs_20080301 a3 where a3.box_id=57 and a3.a_type_id=84 and a3.b_type_id=49));

            +---------------------+

            | count(a1.obslog_id) |

            +---------------------+

            | 40957 |

            +---------------------+

            1 row in set (26.51 sec)

            因为如果有89就一定要有86, 但有89不一定有86. 当然, 我还要计算时间差, 希望不会慢很多.

分页树展主题 · 全看首页 上页
/ 1
下页 末页


有趣有益,互惠互利;开阔视野,博采众长。
虚拟的网络,真实的人。天南地北客,相逢皆朋友

Copyright © cchere 西西河