带有内连接的group by和order by子句的问题

时间:2013-01-22 15:33:56

标签: php mysql inner-join

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

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

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子句 enter image description here

with group by clause enter image description here

但是上表显示了错误的顺序,因为输出必须以#strong> 2013-01-24 02:00:00 为pilotid 1(按时间顺序)返回开始时间。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 ;

这将只为您提供最低开始日期的飞行员。

答案 2 :(得分: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条件。