查询返回最后三个用户的最新条目

时间:2012-03-19 21:42:53

标签: mysql

我有一个查询成功填充了"最新报告" http://budburst.org的框,其中包含最后三个提交的观察结果。

目前,如果一个人提交多个观察,它们会在列表中多次出现。我想要做的是调整查询,以便仅选择最后三个用户最新观察。

这是我当前的疑问:

SELECT tbl_observations.ID,tbl_observations.Observer_ID, 
       tbl_observations.Station_ID, tbl_observations.Species_ID,
       tbl_observations.Species_ID_Fix,tbl_observations.Phenophase_ID,
       tbl_observations.Observation_Date, tbl_observations.Creation_Date,
       tbl_species.Common_Name, tbl_people.First_Name, tbl_people.Last_Name,
       tbl_people.Addr_City, tbl_people.Addr_State, tbl_stations.Station_City,
       tbl_stations.Station_State, tbl_phenophases.Phenophase_Name, 
       tbl_users.UserName
FROM tbl_observations
JOIN tbl_species ON tbl_observations.Species_ID = tbl_species.Species_ID
JOIN tbl_stations ON tbl_observations.Station_ID = tbl_stations.Station_ID
JOIN tbl_people ON tbl_observations.Observer_ID = tbl_people.Person_ID
JOIN tbl_users ON tbl_users.User_ID = tbl_people.Person_ID
JOIN tbl_phenophases ON tbl_observations.Phenophase_ID = tbl_phenophases.Phenophase_ID
WHERE (YEAR(tbl_observations.Observation_Date) = YEAR(CURDATE()))
AND (tbl_species.Common_Name <> '--Other--')
AND (tbl_users.UserName NOT LIKE 'pbbtest%')
ORDER BY tbl_observations.Creation_Date DESC, tbl_observations.ID DESC LIMIT 0,3

1 个答案:

答案 0 :(得分:0)

这是一个未经考验的想法:只需观察者选择MAX观察和分组。

SELECT o.m_ID,tbl_observations.Observer_ID, 
       tbl_observations.Station_ID, tbl_observations.Species_ID,
       tbl_observations.Species_ID_Fix,tbl_observations.Phenophase_ID,
       tbl_observations.Observation_Date, tbl_observations.Creation_Date,
       tbl_species.Common_Name, tbl_people.First_Name, tbl_people.Last_Name,
       tbl_people.Addr_City, tbl_people.Addr_State, tbl_stations.Station_City,
       tbl_stations.Station_State, tbl_phenophases.Phenophase_Name, 
       tbl_users.UserName
FROM tbl_observations
, (select max( id ) m_id, observer_id from tbl_observations group by observer_id ) o
JOIN tbl_species ON tbl_observations.Species_ID = tbl_species.Species_ID
JOIN tbl_stations ON tbl_observations.Station_ID = tbl_stations.Station_ID
JOIN tbl_people ON tbl_observations.Observer_ID = tbl_people.Person_ID
JOIN tbl_users ON tbl_users.User_ID = tbl_people.Person_ID
JOIN tbl_phenophases ON tbl_observations.Phenophase_ID = tbl_phenophases.Phenophase_ID
WHERE tbl_observations.observer_id = o.observer_id
AND tbl_observations.id = o.id
AND (YEAR(tbl_observations.Observation_Date) = YEAR(CURDATE()))
AND (tbl_species.Common_Name <> '--Other--')
AND (tbl_users.UserName NOT LIKE 'pbbtest%')
ORDER BY tbl_observations.Creation_Date DESC, tbl_observations.ID DESC LIMIT 0,3