我需要找到认证的最大日期,将归档字段设置为0.扭曲部分是并非所有认证都有过期日期。现有的更新查询如下:
update user_certs uc1
join ( select user_id, cert_id, ifnull(max(date_expire),max(cert_date)) cert_date
from user_certs
group by user_id,cert_id ) uc2 on (uc1.user_id=uc2.user_id and uc1.cert_id=uc2.cert_id and ifnull(uc1.date_expire,uc1.cert_date)=uc2.cert_date)
set uc1.archive=0
在某些情况下,查询不会考虑同一证书的多个条目。一个可能有一个到期日期,但其他可能有一个更新的cert_date,但到期日期为null,因为该记录尚未从权威数据库导入。
以下查询将考虑该条件,但我无法使其正常工作。即使我将c.expiration值硬编码为36而不是加入,它也会继续无效地使用组函数错误。
update user_certs uc1
join ( select user_id, cert_id, max(case when date_expire > cert_date + interval c.expiration month then date_expire else cert_date end ) cert_date
from user_certs
join certifications c on c.id = cert_id
group by user_id,cert_id ) uc2 on (uc1.user_id=uc2.user_id and uc1.cert_id=uc2.cert_id and max(case when uc1.date_expire > uc1.cert_date + interval uc2.expiration month then uc1.date_expire else uc1.cert_date end )=uc2.cert_date)
set uc1.archive = 0;
所以我需要根据过期日期中的较大者或者几个月内的cert_date +证书过期(c.expiration)找到最新的证书。
更新
在Jim MC的评论的帮助下解决。更正后的查询如下:
update user_certs uc1
join ( select user_id, cert_id, c.expiration, max(case when date_expire > cert_date + interval c.expiration month then date_expire else cert_date end ) cert_date
from user_certs
join certifications c on c.id = cert_id
group by user_id,cert_id ) uc2 on (uc1.user_id=uc2.user_id and uc1.cert_id=uc2.cert_id and (case when uc1.date_expire > uc1.cert_date + interval uc2.expiration month then uc1.date_expire else uc1.cert_date end) = uc2.cert_date)
set uc1.archive=0;