从两个MySQL表中提取数据

时间:2019-07-03 18:26:58

标签: mysql

我有下表:

插槽:

id      Callsign    Received    CTOT    DLY     InsertDate  
1670    AFR115G     021410      1620    OA 83   2019-07-03 06:55:29
1671    AFR115G     021415      1624    OA 83   2019-07-03 07:05:29
1672    AFR115G     021425      1628    OA 83   2019-07-03 07:15:29
1673    AFR115G     021435      1604    OA 83   2019-07-03 07:25:29

呼号:

id      Airline     FltNo   Callsign    Dest    
00001   TOM         1118    TOM1DX      CFU
00002   AFR         1159    AFR115G     CDG

我正在尝试获取给定日期收到的每个唯一呼号从Slots表中收到的最后一个空位,然后使用该呼号从callsigns表中获取航班信息。

我以为我可以一直工作到今天早晨,当时某些插槽没有被恢复。

我当前的查询:

SELECT 
  DISTINCT(Callsigns.Airline), 
  Callsigns.FltNo, 
  Callsigns.Dest, 
  Slots.Callsign, 
  Slots.Received, 
  Slots.CTOT, 
  Slots.DLY 
FROM 
  Slots 
  INNER JOIN(
    SELECT 
      Callsign, 
      MAX(Received) AS LastRcvd, 
      CTOT 
    FROM 
      Slots 
    GROUP BY 
      Callsign
  ) LatestSlot ON Slots.Callsign = LatestSlot.Callsign 
  AND Slots.Received = LatestSlot.LastRcvd 
  AND Slots.Received LIKE = ? 
  INNER JOIN Callsigns ON Callsigns.Callsign = LatestSlot.Callsign 
ORDER BY 
  Airline ASC

我不熟悉联接等的使用,将不胜感激。

预期输出:

Airline FltNo   Dest    Callsign    Received    CTOT    DLY
AF      1159    CDG     AFR115G     021435      1604    OA 83

1 个答案:

答案 0 :(得分:0)

您可以使用以下查询

SELECT 
  c.Airline, 
  c.FltNo, 
  c.Dest, 
  s.Callsign, 
  s.Received, 
  s.CTOT, 
  s.DLY 
FROM 
  Slots s
JOIN Callsigns c ON c.Callsign = s.Callsign
 AND InsertDate=( SELECT max(InsertDate) 
                    FROM Slots
                   WHERE date(InsertDate)='2019-07-03')