我有一个table1
a_id
表PK
,ipaddress
,create_dt
此处ipaddress
为varchar
,create_dt
为datetime
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
的外键
created_dt
是datetime
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
所以从上面的例子中,我的查询应该返回
want to know how to incorporate the logic to consider the row from table2 with latest 'timestamp_val'
我写了以下查询和SELECT
*
FROM table1 a
INNER JOIN table2 b
ON a.a_id = b.a_id
AND DATE(a.create_dt) >= '2017-01-07'
AND b.check_status = 'FAIL'
AND b.check_type = 'check1'
{{1}}
答案 0 :(得分:4)
date()
功能对您没有任何作用。此外,个别比较通常在where
条款中。
然后,您可以使用where
子句中的附加条件执行您想要的操作:
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
);
答案 1 :(得分:0)
SELECT *
FROM table1 a
INNER JOIN table2 b
ON a.a_id = b.a_id
AND date(a.create_dt) >= '2017-01-07'
AND b.check_status = 'FAIL'
AND b.check_type = 'check1'
ORDER BY timestamp_val desc
LIMIT 1