我可以使用某个函数的值作为变量吗

qacovj5a  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(347)

有没有合法的方法来使用这样的变量:

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

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

j2cgzkjk

j2cgzkjk1#

它是一个有效的查询是的,它的语法是正确的,但是按照操作顺序,where子句在select之前应用,所以@diff在执行where子句时可能为空,您可以在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/

vh0rcniy

vh0rcniy2#

使用派生表:

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

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

相关问题