1

我试图了解 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;
4

3 回答 3

1

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

所以这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

因此,您可以将表达式解读为从 Current date and time 减去 4 个月。

您可以在一个简单的选择查询中检查这一点

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

于 2020-12-28T20:06:42.910 回答
1

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

请参阅 DATE_ADD() 的说明。

那里的文档说:

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

您的单位是 YEAR_MONTH,因此根据链接的Temporal Intervals,表达式是要减去的年数和月数,用“-”分隔。

于 2020-12-28T19:57:17.577 回答
1

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

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<>小提琴演示

于 2020-12-28T19:57:24.353 回答