2013-01-22 27 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條件。