我是SQL的新手,我需要一个查询来连接具有特定条件的两个表。这两个表是: 表1:
visitIp serverTimePretty lastActionDateTime
66.87.114.131 8/12/2015 22:59 8/13/2015 2:59
66.87.114.131 8/12/2015 20:32 8/13/2015 0:32
66.87.114.131 8/12/2015 19:34 8/12/2015 23:34
66.87.114.131 12/13/2015 17:36 12/13/2015 22:36
66.87.114.131 4/23/2016 10:25 4/23/2016 14:27
表2:
IPAddress StartDate
66.86.114.131 4/23/2016 8:25
66.70.114.131 4/23/2016 8:25
66.71.114.131 4/23/2016 8:25
66.72.114.131 4/23/2016 8:25
66.87.114.131 4/23/2016 8:25
IP地址是Tabe 2中的主键,它引用了Tabe 1中的VisitIp。现在我想要Table1.visitIp = Table2.IPAddress和Table1.serverTimePretty - Table2.StartDate> = 2小时的列。什么是SQL查询。
答案 0 :(得分:1)
您可以使用DATEDIFF for hours part:
在sql server中执行以下操作SELECT t1.*, t2.*
FROM Table_1 t1 INNER JOIN Table_2 t2
ON t1.visitIp = t2.IPAddress AND
DATEDIFF(hour, t1.serverTimePretty, t2.StartDate) >= 2
编辑
如前所述,您没有提到您使用的是哪种类型的数据库。对于oracle,以下查询将起作用,Oracle直接为您提供两个日期之间的减法:
SELECT t1.*, t2.*
FROM Table_1 t1 INNER JOIN Table_2 t2
ON t1.visitIp = t2.IPAddress AND
floor((date1-date2)*24) >= 2
答案 1 :(得分:0)
在加入条件中DATE_ADD()
使用INTERVAL 2 HOUR
:
SELECT t1.*, t2.*
FROM Table_1 t1 INNER JOIN Table_2 t2
ON t1.visitIp = t2.IPAddress AND
t1.serverTimePretty >= DATE_ADD(t2.StartDate, INTERVAL 2 HOUR)