[英]How do I select datediff between a date and time column and a date column from two different tables in MySQL?
So I have these two data tables, users and logins. 所以我有这两个数据表,用户和登录名。 There is a
registration_date
column for users and a last_login
for logins. 有一个用于用户的
registration_date
列和一个用于登录的last_login
。 I am trying to find the average difference between the two columns from the two tables. 我试图从两个表中找到两列之间的平均差异。 What I believe to be the problem is that the
registration_date
is just date while the last_login
is both date and time. 我认为问题在于,
registration_date
只是日期,而last_login
既是日期和时间。
I first tried: 我首先尝试:
select avg(datediff(u.registration_date, l.last_login)) as avg_acttime from logins l
left join users u on l.userid = u.id and type like '%new%';
My result was null
. 我的结果为
null
。
So I then tried to convert the date and time last_login
column to just date. 因此,我然后尝试将日期和时间
last_login
列转换为date。
select avg(datediff((DATE_FORMAT(u.registration_date,'%d-%m-%y')), (DATE_FORMAT(l.last_login,'%d-%m-%y')))) as avg_acttime from logins l
left join users u on l.userid = u.id and type like '%new%';
The result was again null
. 结果再次为
null
。 I need some serious help getting the difference in days between this date column from one table and a date and time column from another table. 我需要一些认真的帮助,以使一个表中的此日期列与另一表中的日期和时间列之间的天差。
This is too long for a comment. 这个评论太长了。 First, I think you intend for
users
to be the first table. 首先,我认为您打算让
users
成为第一个表。 Then, you don't need a left join
, because avg()
ignores NULL
values anyway. 然后,您不需要
left join
,因为avg()
始终会忽略NULL
值。 So a join
is sufficient: 因此,一个
join
就足够了:
select avg(datediff(u.registration_date, l.last_login)) as avg_acttime
from users u join
logins l
on l.userid = u.id and type like '%new%';
You would get NULL
values either because there are no rows generated by the from
clause or all the rows have a NULL
value for one of the columns. 您可能会得到
NULL
值,因为没有由from
子句生成的行,或者所有行的其中一列都具有NULL
值。 More specifically, I can think of the following possibilities: 更具体地说,我可以想到以下可能性:
logins
or users
has no rows. logins
或users
没有行。 on
conditions. on
条件。 u.registration_date
and l.last_login
are always NULL
for each login. u.registration_date
和l.last_login
中至少有一个始终为NULL
。 Having a datetime
and date
should not result in NULL
values. 具有
datetime
和date
不应导致NULL
值。
Of these, my guess is that no rows match the on
condition. 其中,我猜没有行与
on
条件匹配。 The type
comparison is the most likely cause of failure. type
比较是最可能的失败原因。 Without sample data, it is hard to say more. 没有样本数据,很难说更多。
Your date format %d-%m-%y
will yield very strange results, if any at all. 日期格式
%d-%m-%y
会产生非常奇怪的结果,如果有的话。 Change %d-%m-%y
to 将
%d-%m-%y
更改为
%Y-%m-%d
Mind the capital Y
, or else mysql will format the date with 2 digits for year, what he will then confuse with the day. 注意大写的
Y
,否则mysql将用2位数字表示年份的日期格式,然后他会将其与日期混淆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.