簡體   English   中英

MYSQL:查詢未正確考慮最大日期時間列

[英]MYSQL: Query not properly accounting for max datetime column

我有一個表table1 a_id作為PKipaddresscreate_dt這里ipaddressvarcharcreate_dtdatetime

a_id    ip              create_dt
9205    10.10.10.10     2017-01-07 08:03:32
9206    10.10.10.11     2017-01-06 08:03:32
9207    10.10.10.12     2015-01-07 08:03:32

-超過1000行

我有另一個mysql表,其以下列idPKipcheck_type check_statusa_idcreated_dt :這里a_id是來自table1外鍵,並且timestamp_valTIMESTAMP字段

id      ip             check_type    check_status  a_id    timestamp_val
1       10.10.10.10    check1        FAIL          9205    2017-01-07 10:03:32
2       10.10.10.10    check2        PASS          9205    2017-01-07 10:03:32
3       10.10.10.10    check1        FAIL          9205    2016-11-07 10:03:32
4       10.10.10.10    check2        PASS          9205    2016-11-07 10:03:32
5       10.10.10.11    check1        PASS          9206    2017-01-06 10:03:32
6       10.10.10.11    check2        PASS          9206    2015-01-06 10:03:32

我想要來自table1所有行,其中date(create_dt) >= '2017-01-07'table1.a_id = table2.a_idtable2.check1 = 'FAIL'另外, I only want to consider the row from table2具有最新的timestamp_val

所以從上面的例子中,我的查詢應該返回

a_id    ip              create_dt
9205    10.10.10.10     2017-01-07 08:03:32

我已經編寫了以下查詢,但它並不總是考慮使用max'timestamp_val'從table2中獲取行。

我在某些行中也看到了帶有較舊'timestamp_val'`的值。

SELECT *  
FROM table1 a INNER JOIN
     table2 b
     ON a.a_id = b.a_id
WHERE a.create_dt >= '2017-01-07' AND
      b.check_status = 'FAIL' AND
      b.check_type = 'check1' AND
      b.timestamp_val = (SELECT MAX(b2.timestamp_val)
                         FROM table2 b2
                         WHERE b2.a_id = b.a_id AND
                               b2.check_status = b.check_status AND
                               b2.check_type = b.check_type
                        );

嘗試根據需要獲取最大時間的列使用分組依據,並加入此結果

SELECT *  
FROM table1 a INNER JOIN
     table2 b
     ON a.a_id = b.a_id
INNER JOIN (
  SELECT b2.a_id, b2.check_status, b2.check_type, MAX(b2.timestamp_val) as max_time
  FROM table2 b2
  GROUP BY b2.a_id ,  b2.check_status ,  b2.check_type
  ) t on t.a_id = a.a_id  
      AND  t.check_status=b2.check_status 
      AND t.check_type =b2.check_type
      AND b.timestamp_val = t.max_time
WHERE a.create_dt >= '2017-01-07' AND
      b.check_status = 'FAIL' AND
      b.check_type = 'check1'

嘗試使用此子查詢,現在使用id代替時間戳值:

b.id = (
    SELECT b2.id
    FROM table2 b2
    WHERE
        b2.a_id = b.a_id
        AND b2.check_status = b.check_status
        AND b2.check_type = b.check_type
    ORDER BY b2.timestamp_val desc limit 1
)

將您的timestamp_val更改為DATETIME(6)-它將顯示毫秒。 然后,您將可以正確地按時間排序。 https://dev.mysql.com/doc/refman/5.7/zh-CN/fractional-seconds.html

暫無
暫無

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

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