代码之家  ›  专栏  ›  技术社区  ›  MatthewExpungement

比较两个MySQL表之间的最高值

  •  0
  • MatthewExpungement  · 技术社区  · 8 年前

    我有两个表,search\u history和parse\u history,其中包含多行相同的案例编号,具有不同的时间戳,分别是我上次刮取它的时间戳和我上次解析它的时间戳。我试图编写一个查询,将search\u history表中的案例号的最高时间戳值与parse\u history表中该案例号的最高时间戳值进行比较。如果search\u history中该案例编号的最新条目的时间戳高于parse\u history表中该案例编号的最新条目,则返回该时间戳。

    到目前为止,我看到的所有示例都是使用Max或groupwise Max从单个表中的多个条目中获取最高值。我找不到任何关于比较这两者的内容。

    下面是我的两个表,在下面的示例中,我需要返回案例号4W90B2F,因为最新的search\u历史条目的时间戳高于该案例号的最新parse\u历史条目。

    search_history Table
    ID  CaseNumber  TimeStamp
    1   4W90B2F 2017-09-30 00:25:33
    2   0DB0NGV 2017-09-30 00:15:35
    3   4W90B2F 2017-10-05 00:15:44
    4   0DB0NGV 2017-10-10 00:53:13
    5   4W90B2F 2017-10-20 00:25:34
    
    parse_history Table
    ID  CaseNumber  TimeStamp
    1   4W90B2F 2017-10-01 00:25:33
    2   0DB0NGV 2017-10-02 00:15:35
    3   4W90B2F 2017-10-06 00:15:44
    4   0DB0NGV 2017-10-11 00:53:13
    

    到示例的SQL Fiddle链接 http://sqlfiddle.com/#!9/bc229f

    到目前为止,我的尝试失败了

    SELECT sh.*
    FROM search_history sh
    LEFT JOIN search_history b
    ON sh.CaseNumber = b.CaseNumber AND sh.Timestamp < b.Timestamp
    INNER JOIN
    parse_history as ph
    LEFT JOIN parse_history c
    ON ph.CaseNumber = c.CaseNumber AND ph.Timestamp < c.Timestamp
    WHERE b.CaseNumber IS NULL AND
    c.CaseNumber IS NULL
    LIMIT 50
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   Thorsten Kettner    8 年前

    您可以从查询中选择。因此,从两个表中选择每个案例数的最大时间戳并进行比较。

    select 
    from (select casenumber, max(timestamp) as maxt from search_history group by casenumber) sh
    join (select casenumber, max(timestamp) as maxt from parse_history group by casenumber) ph
      on sh.casenumber = ph.casenumber and sh.maxt > ph.maxt;
    
        2
  •  0
  •   Strawberry    8 年前
    SELECT x.*
      FROM search_history x
      LEFT 
      JOIN parse_history y
        ON y.casenumber = x.casenumber 
       AND y.Timestamp > x.Timestamp
     WHERE y.id IS NULL;