繁体   English   中英

在加入2个mysql表时,如何仅获取第二个表中所需的相关行

[英]While joining 2 mysql tables how to get only the required related row in second table

我在MySQL数据库中具有以下2个表A和B。 当我通过VisitID(A.VisitID = B.VisitID)加入2个表时,我只想从表B中为VisitID提取与最新的Actiondateandtime相关的记录。 例如,VisitID = 85,我想在表B中使用15/10/2014 3:44提取行。对于VisitID = 86,我只想在表B中使用09/10/2014 1:28提取行。

表A:

VisitID       VisitTitle                     VisitSummary                        Conclusion

85            Go to Paddy Field 1            Checked Temperatures                1
86            Soil Quality Checked           Checked PHP of different soil       2
87            Go to Paddy Field 2            Collected Soil samples              0

表B:

RefID   VisitID      ActionDesc                                 Actiondateandtime

1       85           Submiited to Management                    9/10/2014  12:03
2       86           Sent to lab                                9/10/2014  1:06
3       86           Sent to lab                                9/10/2014  1:07
4       86           Sent to lab                                9/10/2014  1:21
5       86           Sent to lab                                9/10/2014  1:28
6       87           Followed with Soil scientist               9/10/2014  1:32
7       87           Followed with Soil scientist               9/10/2014  1:33
8       85           Submitted to Management                    15/10/2014 3:44

我想要这两个表联接后的结果

A.VisitID  A.VisitTitle           A.Conclusion  B.RefID   B.VisitID  B.Actiondateandtime

85         Go to Paddy Field 1    1             8         85         15/10/2014 3:44
86         Soil Quality Checked   2             5         86         9/10/2014 1:28
87         Go to Paddy Field 2    0             7         87         9/10/2014 1:33

要获得所需结果,需要哪些MySQL代码?

尝试这个.....

select *
from Table At1
inner join TableB t2 on t1.VisitID =t2.VisitID
where t2.Actiondateandtime in (select  max(Actiondateandtime )
                               from TableB
                               group by VisitID)

检查这个小提琴http://sqlfiddle.com/#!2/e4f80/2

一种选择是join使用表背到自己max骨料度日visitid分组的最大日期:

select a.visitid, a.visittitle, a.conclusion, b.refid, b.actiondateandtime
from tablea a 
  join tableb b on a.visitid = b.visitid
  join (
    select visitid, max(actiondateandtime) actiondateandtime
    from tableb 
    group by visitid
    ) c on b.visitid = c.visitid and b.actiondateandtime = c.actiondateandtime

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM