我可以将变量与某些函数的值一起使用吗

时间:2018-12-05 06:32:44

标签: mysql

使用这样的变量是否合法:

SELECT dr.id, @diff:=DATEDIFF(NOW(), DATE_ADD(dr.dt, INTERVAL dr.payment_session DAY))
FROM `dst_request` as dr
WHERE @diff >= 0 OR @diff <=5

它不会抛出这样的错误,但是也不会返回正确的结果。它是有效的查询吗?谢谢!

2 个答案:

答案 0 :(得分:1)

使用派生表:

SELECT 
    id, 
    diff
FROM (
        SELECT
            dr.id,
            DATEDIFF(NOW(), DATE_ADD(dr.dt, INTERVAL dr.payment_session DAY)) as diff
         FROM `dst_request` as dr
) as t
WHERE diff >= 0 OR diff <=5

如果有语法或格式错误,请原谅我,因为我在浴缸里用手机转录了这个错误。这个概念是正确的。

答案 1 :(得分:1)

这是一个有效的查询吗,在语法上正确,但是按照操作顺序在select之前应用了where子句,因此在执行where子句时@diff可能为null,您可以在where子句中应用计算以克服这个。

SELECT dr.id, DATEDIFF(NOW(), DATE_ADD(dr.dt, INTERVAL dr.payment_session DAY)) diff
FROM `dst_request` as dr
WHERE DATEDIFF(NOW(), DATE_ADD(dr.dt, INTERVAL dr.payment_session DAY)) >= 0 
OR DATEDIFF(NOW(), DATE_ADD(dr.dt, INTERVAL dr.payment_session DAY)) <=5

https://www.eversql.com/sql-order-of-operations-sql-query-order-of-execution/