2012-05-11 108 views
0

我有一個查詢,顯示基於一個人的id(運動員)的比賽結果列表。我查詢了數據庫,以便按時間(性能)和事件(eventid)順序列出人員的比賽,但我努力將其設置爲子查詢,以便我可以將結果分組後,以最快的速度離開我每個eventid的性能。這是我到目前爲止:MySQL子查詢組按

$id = $_GET['id']; 
$query = sprintf("SELECT events.eventcode, meetings.meetingid, meetings.meetingname, meetings.location, meetings.meetingdate, DATE_FORMAT(meetings.meetingdate,'%%d %%b %%Y') AS date, results.performance, results.unit, results.wind, agegroups.agegroup 
FROM results 
JOIN athletes ON athletes.athleteid = results.athleteid 
JOIN meetings ON meetings.meetingid = results.meetingid 
JOIN events ON events.eventid = results.eventid 
JOIN agegroups ON agegroups.agegroupid = results.agegroupid 
WHERE results.athleteid='$id' AND events.eventtype = 'track' ORDER BY results.eventid asc, results.performance asc, meetings.meetingdate desc"); 

這工作正常,並以正確的順序顯示所有相關的條目。然後我嘗試將它轉換爲子查詢,以便我可以使用GROUP BY,但沒有成功。這是我試圖去用它:

$id = $_GET['id']; 
$query = sprintf("SELECT * FROM (SELECT events.eventcode, meetings.meetingid, meetings.meetingname, meetings.location, meetings.meetingdate, DATE_FORMAT(meetings.meetingdate,'%%d %%b %%Y') AS date, results.performance, results.unit, results.wind, agegroups.agegroup 
FROM results 
JOIN athletes ON athletes.athleteid = results.athleteid 
JOIN meetings ON meetings.meetingid = results.meetingid 
JOIN events ON events.eventid = results.eventid 
JOIN agegroups ON agegroups.agegroupid = results.agegroupid 
WHERE results.athleteid='$id' AND events.eventtype = 'track' ORDER BY results.eventid asc, results.performance asc, meetings.meetingdate desc) AS t1 
GROUP BY t1.eventid"); 

然而,這給了我這一條錯誤:在「組聲明」未知列「t1.eventid」

任何幫助是極大的讚賞

+0

嗨,如果你在mysql中使用'GROUP BY'然後「Group By」中的'fieldname'必須位於'selected Column'中。使用'select *,t1.eventid from(select..' ..謝謝 –

回答

0

您在子查詢中未選擇eventid。如果不在那裏,你如何分組?

SELECT events.eventid,events.eventcode, 
meetings.meetingid, meetings.meetingname, 
meetings.location, meetings.meetingdate, 
DATE_FORMAT(meetings.meetingdate,'%%d %%b %%Y') AS date, 
results.performance, results.unit, results.wind, 
agegroups.agegroup 
....... 
0

那是因爲你沒有在子查詢列,嘗試添加列子選擇:

$id = $_GET['id']; 
$query = sprintf("SELECT * FROM (SELECT events.eventid, events.eventcode, meetings.meetingid, meetings.meetingname, meetings.location, meetings.meetingdate, DATE_FORMAT(meetings.meetingdate,'%%d %%b %%Y') AS date, results.performance, results.unit, results.wind, agegroups.agegroup 
FROM results 
JOIN athletes ON athletes.athleteid = results.athleteid 
JOIN meetings ON meetings.meetingid = results.meetingid 
JOIN events ON events.eventid = results.eventid 
JOIN agegroups ON agegroups.agegroupid = results.agegroupid 
WHERE results.athleteid='$id' AND events.eventtype = 'track' ORDER BY results.eventid asc, results.performance asc, meetings.meetingdate desc) AS t1 
GROUP BY t1.eventid");