具有内连接的2个表的mysql查询

时间:2016-08-23 22:52:53

标签: mysql sorting datetime inner-join columnsorting

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

  1. 表A列:TA ID,Truck_Num,Serial_Num
  2. 表B列:TB ID,Serial_Num,Lat,Long,DateTime
  3. 期望的输出

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

    使用联接查询

    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);
    

2 个答案:

答案 0 :(得分:2)

这将显示每辆卡车的最新项目。如果要显示的其他信息在所有行中相同,则可以将其放在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

答案 1 :(得分:0)

它应该有效,你可以查看这个问题: Select only one row with max field with One-Many Relationship Table

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