[英]mysql difference between dates expressed in years
I've been using the following for some time to avoid the fact that DATEDIFF
doesn't account for leap years. 为了避免
DATEDIFF
不代表leap年这一事实,我一直在使用以下内容。
"select
year(now())
- year(`birthdate`)
- (date_format(now(), '%m%d') < date_format(`birthdate`, '%m%d');"
But I've never really understood exactly how it works, in particular, what the <
operator does here? 但是我从来没有真正真正了解过它是如何工作的,尤其是
<
运算符在这里做什么?
The <
is a comparison operator. <
是比较运算符。
So that last line is evaluated as a boolean expression. 因此,最后一行被评估为布尔表达式。 The expression on the left is being compared to the expression on the right, and the comparison is returning either NULL, 0 or 1. (MySQL returns 1 for TRUE and 0 for FALSE.)
正在将左侧的表达式与右侧的表达式进行比较,并且比较返回NULL,0或1。(对于TRUE,MySQL返回1;对于FALSE,MySQL返回0。)
The net effect of that last line is that's subtracting either a "0"
or a "1"
(if birthdate is not null.) 最后一行的净效果是减去
"0"
或"1"
(如果生日不是null)。
To see this in action, try running this query: 要查看实际效果,请尝试运行以下查询:
SELECT '0501' < '1031' AS foo
The result of the boolean expression can be referenced in another expression, for example: 布尔表达式的结果可以在另一个表达式中引用,例如:
SELECT 24 - ( '0501' < '1031' ) AS foo
If birthdate
is non-null, the expression: 如果
birthdate
是非null,则表达式:
(date_format(now(),'%m%d') < date_format(`birthdate`,'%m%d')
Is equivalent to: 等效于:
IF((date_format(now(),'%m%d') < date_format(`birthdate`,'%m%d'),1,0)
and equivalent to: 相当于:
CASE WHEN (date_format(now(),'%m%d') < date_format(`birthdate`,'%m%d')
THEN 1
ELSE 0
END
The last boolean part (< comparsion) makes difference between asking before/after birthday. 最后一个布尔值部分(<比较)使生日前后的询问有所不同。 (Adds 1 OR 0)
(加1或0)
Try: 尝试:
SELECT 10 - 7 - true
= 2 SELECT 10 - 7 - true
= 2
SELECT 10 - 7 - false
= 3 SELECT 10 - 7 - false
= 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.