条件mysql insert

m1m5dgzv  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(442)

我开发这个解决方案,如果有其他更好的解决方案请分享。

  1. SET @num = (SELECT count(distinct(detalle)) as 'distintos'
  2. FROM
  3. (SELECT detalle, SUBSTRING(momento, 1, 10) as momento FROM t2
  4. where detalle in ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I')) AS T1
  5. where momento like (Select SUBSTRING(momento, 1, 10) as momento from t2 order by momento desc limit 1));
  6. INSERT INTO `t2`.`log_reportes` (`accion`, `detalle`)
  7. SELECT 'REVISION AUTOMATICA', 'ERROR' FROM DUAL
  8. WHERE @num = 6;
  9. INSERT INTO `t2`.`log_reportes` (`accion`, `detalle`)
  10. SELECT 'REVISION AUTOMATICA', 'OK' FROM DUAL
  11. WHERE @num = 7;
gfttwv5a

gfttwv5a1#

它可以一次完成 INSERT 查询。

  1. INSERT INTO `t2`.`log_reportes` (`accion`, `detalle`)
  2. SELECT 'REVISION AUTOMATICA', IF(distintos = 6, 'ERROR', 'OK')
  3. FROM (SELECT COUNT(DISTINCT detalle) as distintos
  4. FROM (SELECT detalle, SUBSTRING(momento, 1, 10) as momento FROM t2
  5. where detalle in ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I')) AS T1
  6. where momento = (Select MAX(SUBSTRING(momento, 1, 10)) from t2)
  7. ) AS t3
  8. WHERE distintos IN (6, 7)

我还简化了子查询

  1. (Select SUBSTRING(momento, 1, 10) as momento from t2 order by momento desc limit 1)

变成正义

  1. (Select MAX(SUBSTRING(momento, 1, 10)) from t2)

如果 momento 是一个 DATETIME , SUBSTRING(momento, 1, 10) 更恰当的做法是 DATE(momento) .

展开查看全部

相关问题