2013-01-22 26 views
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子句,该查询很有用。它通过条款 enter image description here

与group by子句 enter image description here

返回以下结果

与出组但上面的表格显示了错误的顺序,因为输出必须返回启动时间设为针对pilotid 1的2013-01-24 02:00:00(时间顺序)。

+2

尝试将'A.start'更改为'MIN(A.start)' – datasage

+0

感谢@datasage它的工作。 –

+0

我有另一个问题,如果我使用MIN(A.start),其余的列值被改变。 –

回答

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

试试这个:

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 ; 

这会给你以最小的开始日期只有那些飞行员。

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条件。