首页 > 解决方案 > 如何比较MySql中的初始记录和最新记录

问题描述

我试图在同一个查询中加入以下三个表,并尝试获取初始值和最终值的状态基础。

表格1

ID1        Date1                      Value1
T-1        2019-12-15 12:14:13        10000
T-2        2019-12-15 16:17:24        11000
T-3        2019-12-17 10:01:11        15000
T-4        2019-12-18 21:10:21        17000

表2

ID2        Date2                      Value2    Seq
T-1        2019-12-16 19:18:11        10000     1
T-2        2019-12-16 16:33:24        12000     1
T-2        2019-12-17 15:21:21        12000     2
T-2        2019-12-17 13:10:18        18000     3
T-2        2019-12-18 19:18:07        11000     4
T-3        2019-12-17 11:11:11        14000     1
T-3        2019-12-18 22:18:08        13000     2
T-3        2019-12-18 19:07:01        13000     3
T-4        2019-12-19 21:38:15        17000     1
T-4        2019-12-19 21:45:20        17000     2

表3

ID3         Date3                     Value3
T-1        2019-12-16 19:18:11        10000 
T-2        2019-12-18 19:18:07        11000
T-3        2019-12-18 19:07:01        13000
T-4        2019-12-19 21:45:20        17000

很明显Table3包含最新记录,我想使用上表得出以下详细信息:

所需输出:

ID3     Value1        Value3          Initial_Date           Latest_Date           Status
T-1     10000         10000           2019-12-16 19:18:11    2019-12-16 19:18:11   TRUE
T-2     11000         12000           2019-12-16 16:33:24    2019-12-18 19:18:07   FALSE
T-3     15000         14000           2019-12-17 11:11:11    2019-12-18 19:07:01   FALSE
T-4     17000         17000           2019-12-19 21:38:15    2019-12-19 21:45:20   TRUE

我尝试了以下查询,但没有成功: MySQL 版本是5.7.25

select ID3,Value1, Value2, Date2 As Initial_Date, Date3 As Final_Date
from Table1 t1
Left Join Table2 t2 on t1.ID1=t2.ID2
Left Join Table3 t3 on t2.ID2=t3ID3
where t2.Seq=1
group by t3.ID3;

标签: mysql

解决方案


对于此示例数据,您只需group by从查询中删除子句和Status列,如下所示:

select t3.ID3, t1.Value1, t2.Value2, 
  t2.Date2 As Initial_Date, t3.Date3 As Final_Date, 
  t1.Value1 = t2.Value2 Status
from Table1 t1
Left Join Table2 t2 on t1.ID1=t2.ID2
Left Join Table3 t3 on t2.ID2=t3.ID3
where t2.Seq = 1

如果您希望Status列为TRUEor FALSE

select t3.ID3, t1.Value1, t2.Value2, 
  t2.Date2 As Initial_Date, t3.Date3 As Final_Date, 
  case when t1.Value1 = t2.Value2 then 'TRUE' else 'FALSE' end Status
from Table1 t1
Left Join Table2 t2 on t1.ID1=t2.ID2
Left Join Table3 t3 on t2.ID2=t3.ID3
where t2.Seq = 1

请参阅演示
结果:

> ID3 | Value1 | Value2 | Initial_Date        | Final_Date          | Status
> :-- | -----: | -----: | :------------------ | :------------------ | :-----
> T-1 |  10000 |  10000 | 2019-12-16 19:18:11 | 2019-12-16 19:18:11 | TRUE  
> T-2 |  11000 |  12000 | 2019-12-16 16:33:24 | 2019-12-18 19:18:07 | FALSE 
> T-3 |  15000 |  14000 | 2019-12-17 11:11:11 | 2019-12-18 19:07:01 | FALSE 
> T-4 |  17000 |  17000 | 2019-12-19 21:38:15 | 2019-12-19 21:45:20 | TRUE  

另外,既然你有where t2.Seq = 1那么到 Table2 的连接是一个内连接,而不是一个左连接。


推荐阅读