Mysql内连接查询2个表



我想连接表A和表B,并显示每辆卡车的最新条目。

  1. 表A列:TA ID,Truck_Num,Serial_Num
  2. 表B列:TB ID,Serial_Num,Lat,Long,DateTime

期望输出

 Truck   |     DateTime     |    Serial_Num   |       Lat   |      Long                
   1     |     datestamp    |       123       |        1    |       -1                                     
   2     |     datestamp    |       456       |        2    |       -2

使用join查询

SELECT a.Truck b.Lat b.Long b.DateTime FROM TB as b INNER JOIN TA AS a a.Serial_Num=b.Serial_Num; 

我试过了,但它只给我最近条目的时间。

SELECT a.Truck b.Lat b.Long b.DateTime FROM TB as b INNER JOIN TA AS a a.Serial_Num=b.Serial_Num WHERE b.DateTime = (SELECT MAX(b.DateTime) FROM TB tb WHERE a.Truck_Num=Truck_Num);

这将显示每个Truck最近的项目。如果你想显示的其余信息在所有行中都是相同的那么你可以把它放在group by子句中,如果不是,那么你必须与这个结果进行连接

SELECT Serial_Num, MAX(DateTime) FROM TB GROUP BY Serial_Num;

如果数据不相等且不能将其放在group by子句

上,则必须执行此连接
SELECT Truck_Num, Lat, Long, maxDateTime FROM TB as b 
   INNER JOIN TA AS a ON a.Serial_Num=b.Serial_Num
   INNER JOIN (SELECT Serial_Num, MAX(DateTime) as maxDateTime
               FROM TB GROUP BY Serial_Num) as c 
               ON b.Serial_Num=c.Serial_Num AND maxDateTime = DateTime

它应该工作,你可以检查这个问题:单多关系表

SELECT
    ta.Truck,
    tb.Lat,
    tb.Long,
    MAX(tb.DateTime),
    ta.Serial_Num as Serial_Num
FROM
    TB as tb
INNER JOIN
    TA as ta
ON (tb.Serial_Num = ta.Serial_Num)
GROUP BY
    tb.Serial_Num

相关内容

  • 没有找到相关文章

最新更新