MySQL 上的 INTERVAL '0-0' YEAR_MONTH 是什么意思?

What is the meaning of INTERVAL '0-0' YEAR_MONTH on MySQL?

我试图理解 MySQL 存储过程,但我不理解 YEAR_MONTH 的用法。 INTERVAL '0-0' YEAR_MONTH 和 INTERVAL '0-4' YEAR_MONTH 是什么意思? 它的用途是什么?

存储过程上的查询是这样的:

SELECT remunerations.id_princ,
       remunerations.id_cont,
       customer.t_contraco,
       remunerations.id_ct,
       ABS(SUM(remunerations.item1)) AS item1,
       ABS(SUM(remunerations.item2)) AS item2,
       ABS(SUM(remunerations.item3)) AS item3
FROM customer
     RIGHT OUTER JOIN remunerations ON (customer.id_cont = remunerations.id_cont)
     RIGHT OUTER JOIN contractuals ON (remunerations.id_ct = contractuals.id_ct)
WHERE remunerations.id_princ = var_princ AND
      customer.active_cont = 1 AND
      customer.deactive_princ = 1 AND
      DATE_FORMAT(CONCAT(remunerations.anyo_trab, '-', remunerations.mes_trab, '-15'), "%Y-%m-%d") IN ((
              SELECT DATE_SUB(CONCAT(MAX(rm.anyo_trab),'-', MAX(rm.mes_trab),'-15'), INTERVAL '0-0' YEAR_MONTH) AS fecha2
              FROM
                remunerations rm
              WHERE rm.anyo_trab = YEAR (date_sub (NOW(), INTERVAL '0-4' YEAR_MONTH)) AND
                    rm.id_princ = var_princ AND
                    rm.id_cont = remunerations.id_cont
      )) AND
      (remunerations.finiquito_planilla IS NULL OR remunerations.finiquito_planilla >= var_fecha)
GROUP BY remunerations.id_princ,
         remunerations.id_cont,
         customer.elorden,
         remunerations.id_ct;

这是 DATE_SUB 的一个参数。查看 documentation ,它说:

See the description for DATE_ADD().

documentation there 表示:

DATE_ADD(date,INTERVAL expr unit), DATE_SUB(date,INTERVAL expr unit)

你的单位是YEAR_MONTH,所以根据链接Temporal Intervals,表达式是要减去的年数和月数,用'-'分隔。

它似乎用于将值转换为日期数据类型:

SELECT DATE_SUB(CONCAT(MAX(rm.anyo_trab),'-', MAX(rm.mes_trab),'-15'), 
            INTERVAL '0-0' YEAR_MONTH) AS fecha2

作为

CONCAT(MAX(rm.anyo_trab),'-', MAX(rm.mes_trab),'-15'

绝对是文字。添加 0 文字不会更改值,除非隐式转换。实际上它与以下内容相同:

SELECT CAST(CONCAT(MAX(rm.anyo_trab),'-', MAX(rm.mes_trab),'-15') AS DATE) ...

db<>fiddle demo

基本上 DATE_SUB() 函数在 SQL 中用于从日期中减去 time/date 间隔,然后 returns 日期。

所以这个date_sub (NOW(), INTERVAL '0-4' YEAR_MONTH)意味着

date_sub - function to subtract    
NOW() -  would be the current DATE and TIME
INTERVAL - value to be added or subtracted
'0-4' - corresponds to YEAR=0 & MONTH=4

因此您可以将表达式解读为从当前日期和时间减去 4 个月。

您可以在一个简单的 Select 查询中查看

此外,请查看官方文档https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html#function_date-add