连接到MYSQL表的最后一行

时间:2019-02-15 06:22:21

标签: mysql

我想把产犊表和挤奶表合并为两个表;在产犊表中,一只动物可以有多个产犊日期,我想选择最后一个合适的日期并加入我的两个表,以便每条奶记录都具有正确的产犊日期。

我的两个表如下:

产犊表称为产犊

animalid calvingdate
    '1', '1990-12-24'
    '1', '1994-08-19'
    '1', '1997-01-01'
    '2', '1997-01-22'
    '2', '1999-01-13'

称为testmilking的挤奶表

animalid   milkdate    milkyield
    '1', '1997-02-19', '17.90'
    '1', '1997-03-21', '18.00'
    '1', '1998-05-01', '13.70'

我用来生成摘要的查询

SELECT testmilking.animalid,calvingdate,milkdate, milkyield FROM testmilking 
INNER JOIN calving on testmilking.animalid = calving.animalid
GROUP BY concat(animalid,calvingdate,milkdate)

正确的输出应如下,产犊和挤奶日期之间的日期差应小于500

animalid calvingdate milkdate, milkyield 
'1','1997-01-01', '1998-05-01', '13.70'

创建语句

测试日

CREATE TABLE `testmilking` (
  `AnimalId` int(11) NOT NULL,
  `MilkDate` date NOT NULL,
  `MilkYield` decimal(5,2) NOT NULL),
  PRIMARY KEY (`AnimalId`,`MilkDate`),
  CONSTRAINT `FKAnimal_TestMilking` FOREIGN KEY (`AnimalId`) REFERENCES `animal` (`AnimalId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

分娩台

CREATE TABLE `calving` (
  `AnimalId` int(11) NOT NULL,
  `CalvingDate` date NOT NULL),
  CONSTRAINT `FKAnimal_Calving` FOREIGN KEY (`AnimalId`) REFERENCES `animal` (`AnimalId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

3 个答案:

答案 0 :(得分:0)

您应在DATEDIFF条件下使用简单的JOIN。它返回两个日期之间的天数(请注意,您应该将适当的数据类型应用于日期列!):

SELECT testmilking.animalid,max(calvingdate),milkdate, milkyield FROM testmilking 
INNER JOIN calving on testmilking.animalid = calving.animalid
AND ABS(DATEDIFF(calvingdate, milkdate)) < 500
group by testmilking.animalid, milkdate, milkyield

答案 1 :(得分:0)

select t1.animalid, 
      t1.calvingdate,
       t2.milkdate,
       milkyield
from (select animalid, max(calvingdate)
              from claving
              group by animalid
      )t1                  
join (Select animalid,milkdate, milkyield
      from testmilking 
      where (animalid, milkdate) in 
                         (Select animalid, max(milkdate)
                          from testmilking 
                          group by animalid
                         )
     ) t2
on t1.animalid = t2.animalid
where ABS(DATEDIFF(calvingdate, milkdate)) < 500    

答案 2 :(得分:0)

只需尝试一下,

SELECT testmilking.animalid,max(calvingdate),max(milkdate),(SELECT milkyield FROM 
testmilking WHERE milkdate=MAX(milkdate)) as milkyield FROM testmilking 
LEFT JOIN calving on testmilking.animalid = calving.animalid and
ABS(DATEDIFF(calvingdate, milkdate)) < 500
GROUP BY calvingdate,milkdate,testmilking.animalid