我试图在同一查询中联接以下三个表,并尝试获取状态基础的初始值和最终值。
表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
包含最新记录,我想使用上面的表得出以下提到的详细信息:
Value2
= 1的Seq
小于或大于Value1
,则将其显示为FALSE Seq
= 1以及每个唯一的ID
的最新日期必需的输出:
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;
答案 0 :(得分:1)
对于此示例数据,您所需要做的就是从查询中删除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
列为TRUE
或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
请参见demo。
结果:
> 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的联接是内部联接,而不是左联接。