mysql - 仅比较最新记录

标签 mysql

我想创建一个触发器,如果​​满足条件,则将新记录更新到第二个表

TableA

#ID,animalid,calvdate,lactation
1,animal1, 2016-03-15,1
2,animal1, 2017-06-09,2

TableB
#animalid, calvdate, milkmorning, milkevening
animal1,2017-07-09,2,2
animal1,2018-08-27,3,3

我想将新的正确的 Calvdate 更新到表中。以下是我的查询

SELECT animalid,calvdate,lactation FROM tableB
inner join tableA on tableB.animalid = tableA.animalid
where TO_DAYS(tableA.calvdate) -TO_DAYS(tableB.calvdate) > 400
group by animalid and calvdate

Expected Output 

  #ID,animalid,calvdate,lactation
    1,animal1, 2016-03-15,1
    2,animal1, 2017-06-09,2
    3,animal1, 2018-08-27,3

注意:哺乳必须自动生成

预期输出有 3 条记录,因为新的 calvdate 与上一个 calvdate 相比满足条件并且大于 400 天

最佳答案

我在这里假设了一些事情。

1.每个动物ID的哺乳期将分别递增。 2.只需与每个动物ID中的最新产犊日期进行比较,如果差异大于400天,则插入B中的记录。

<insert into A>
SELECT B.animalid,B.calvdate,init.lactation
FROM 
(SELECT MAX(calvdate) as calvdate, animalid FROM tableB GROUP BY animalid) B
left join 
(SELECT MAX(calvdate) as calvdate, MAX(lactation) + 1 as lactation, animalid FROM tableA GROUP BY animalid) init
on 
B.animalid = init.animalid
AND DATEDIFF(B.calvdate,init.calvdate) > 400
WHERE init.animalid IS NOT NULL

您可以在此处查看 SQL Server 模拟:https://rextester.com/BLT38001

关于mysql - 仅比较最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55611286/

相关文章:

php - 按多个属性选择产品,使用 AND 代替 OR 连接器,数据模型 EAV

php - 为每个帖子选择 3 条评论

mysql - sql查询具有特殊字符的列

mysql - 将 mysql 查询转换为 codeigniter 事件记录

php - 需要提取今天的数据,但日期是时间戳。我该怎么做呢?

mysql - 我可以在 ~/.my.cnf 中有多个 [mysqldump] 部分吗?

mysql - 如何使用两个链接表编写一个相对简单的 UPDATE 查询

android:通过 php 连接 mysql(WAMP 设置)- 应用程序崩溃

mysql - Gradle 连接到 Docker-Container 中的 MySql 失败

mysql - 使用子查询 MySQL 插入 INTO