我有一个表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
:
这里a_id
是来自table1
id ip check_type check_status a_id
1 10.10.10.10 check1 FAIL 9205
2 10.10.10.10 check2 PASS 9205
3 10.10.10.11 check1 PASS 9206
4 10.10.10.11 check2 PASS 9206
我想要来自 table1
的所有行,其中 date(create_dt) >= '2017-01-07'
和
table1.a_id = table2.a_id
和 table2.check1 = 'FAIL'
所以从上面的例子来看,我的查询应该返回
a_id ip create_dt
9205 10.10.10.10 2017-01-07 08:03:32
我编写了以下查询,想知道是否有更好的方法来编写查询。 下面的查询似乎慢一点
SELECT *
FROM table1 a
INNER JOIN table2 b
ON a.a_id = b.a_id
WHERE date(a.create_dt) >= '2017-01-07'
AND
b.check_status = 'FAIL'
AND b.check_type = 'check1'
最佳答案
I have written the following query and want to know if there is some better way to write the query
您的查询看起来不错。您使用特定键连接了两个表并应用了所需的 where 子句。因此,我的建议是不要像 date(a.create_dt)
那样转换日期。将 create_dt
列转换为 date
字段。应用转换可能会导致查询性能降低。只要有可能,尽量避免这种类型的转换。
关于MySQL:从另一个表查找服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48162728/