【问题标题】:Compare Highest Values Between Two MySQL Tables比较两个 MySQL 表之间的最大值
【发布时间】:2017-10-27 13:50:24
【问题描述】:

我有两个表,search_history 和 parse_history,它们包含多行相同的案例编号,具有不同的时间戳,分别是我上次抓取它的时间和上次解析它的另一个表。我正在尝试编写一个查询,它将 search_history 表中案例编号的最高时间戳值与 parse_history 表中该案例编号的最高时间戳值进行比较。如果 search_history 中该案例编号的最新条目的时间戳高于 parse_history 表中该案例编号的最新条目,则返回。

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

下面是我的两个表,在下面的示例中,我需要返回案例编号 4W90B2F,因为最近的 search_history 条目的时间戳高于该案例编号的最新 parse_history 条目。

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

【问题讨论】:

标签: mysql sql max


【解决方案1】:

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

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】:
    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-14
      • 2012-11-05
      • 2021-06-19
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 2012-06-21
      相关资源
      最近更新 更多