0

我有两张桌子,即位置和飞行员。我一直在尝试根据 location_id 获取数据,即按日期(计划日期)选择以特定 location_id 顺序飞行的飞行员。

我正在使用 group by,因为我只需要显示不同的飞行员。

select  B.*, 
    A.rather_to_be_flying_now,
    A.here_now,
    A.flying,
    A.when,
    A.my_favorite,
    A.start,
    A.end,
    A.Locationid
from locations A 
inner join pilots B 
    on A.Pilotid=B.pilot_id 
where A.VenueID='$venueid' 
    and (A.flying='1' or A.here_now='1') 
group by A.Pilotid 
ORDER BY A.start

如果我不包含 group by 子句,则查询效果很好。它返回以下结果

没有 group by 子句 在此处输入图像描述

使用 group by 子句 在此处输入图像描述

但是上表显示的顺序错误,因为对于 Pilotid 1(时间顺序) ,输出必须返回开始时间为2013-01-24 02:00:00 。

4

3 回答 3

2

您可以使用MIN()

select  B.*, 
    A.rather_to_be_flying_now,
    A.here_now,
    A.flying,
    A.when,
    A.my_favorite,
    MIN(A.start) as start,
    A.end,
    A.Locationid
from locations A 
inner join pilots B 
    on A.Pilotid=B.pilot_id 
where A.VenueID='$venueid' 
    and (A.flying='1' or A.here_now='1') 
group by A.Pilotid 
ORDER BY A.start
于 2013-01-22T15:41:13.577 回答
1

试试这个:

SELECT
  B.*,
  A.rather_to_be_flying_now,
  A.here_now,
  A.flying,
  A.when,
  A.my_favorite,
  A.start,
  A.end,
  A.Locationid
FROM locations A 
INNER JOIN
(
   SELECT pilotid, MIN(start) MinStart
   FROM locations
   GROUP BY pilotid
) a2  ON A.pilotId = a2.pilotId
     AND a.start   = a2.minStart 
INNER JOIN pilots B on A.Pilotid = B.pilot_id 
WHERE A.VenueID = '$venueid' 
  AND (A.flying='1' OR A.here_now='1');
ORDER BY A.start ;

这将只为您提供那些具有最短开始日期的飞行员。

于 2013-01-22T15:37:19.273 回答
1

试试这个查询 -

SELECT
  p.pilit_id, l.location_id, l.start
FROM pilots p
  JOIN (SELECT l1.*
        FROM locations l1
        JOIN (SELECT location_id, MIN(start) start
              FROM locations
              GROUP BY locations) l2
        ON l1.id = l2.id AND l1.start = l2.start
        ) l
    ON l.pilot_id = p.pilot_id
GROUP BY p.pilot_id

添加您的 WHERE 条件。

于 2013-01-22T15:42:29.927 回答