簡體   English   中英

比較兩個MySQL表之間的最大值

[英]Compare Highest Values Between Two MySQL Tables

我有兩個表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

您可以從查詢中選擇。 因此,從兩個表中選擇每個案例編號的最大時間戳並進行比較。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM