mysql:查询未正确计算max datetime列

gkn4icbw  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(345)

我有一张table
table1 a_id 作为 PK , ipaddress , create_dt 在这里 ipaddressvarchar , create_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表,它有以下列 `id` 作为 `PK` ,  `ip` , 
check_type `check_status` ,  `a_id` 以及 `created_dt` :此处 `a_id` 外键来自 `table1` 以及 `timestamp_val` 是 `TIMESTAMP` 领域

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_id` 以及 `table2.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

我已经编写了以下查询,但它并不总是考虑表2中最大'timestamp\u val'的行`
我在某些行中也看到了带有旧的'timestamp\u 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
);

p5cysglq

p5cysglq1#

将时间戳值更改为datetime(6)-在这里它将显示毫秒。然后,您将能够按时间正确排序。https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html

zhte4eai

zhte4eai2#

请尝试使用一个基于所需列的group by来获取最大时间并加入此结果

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'
zsohkypk

zsohkypk3#

尝试此子查询,现在使用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
)

相关问题