2012-03-26 41 views
0

我已經在MySQL我怎麼能子組我的MySQL結果

+-----------------+-------------+------+-----+---------+----------------+ 
| Field   | Type  | Null | Key | Default | Extra   | 
+-----------------+-------------+------+-----+---------+----------------+ 
| id    | int(11)  | NO | PRI | NULL | auto_increment | 
| user_profile_id | int(11)  | NO | MUL | NULL |    | 
| latitude  | float(10,6) | YES |  | NULL |    | 
| longitude  | float(10,6) | NO |  | NULL |    | 
| modified  | datetime | YES |  | NULL |    | 
| created   | datetime | YES |  | NULL |    | 
+-----------------+-------------+------+-----+---------+----------------+ 

我想在那裏我通過user_profile_id s的名單,我也得到了他們的最新唱片回來做一個查詢下表。每個user_profile_id有多個記錄

sql : select id,user_profile_id,latitude,longitude,modified,created from user_locations where user_profile_id in(1044,1259); 

    +----+-----------------+-----------+-------------+---------------------+-------------------- -+ 
| id | user_profile_id | latitude | longitude | modified   | created    | 
+----+-----------------+-----------+-------------+---------------------+---------------------+ 
| 14 |   1044 | 49.276867 | -123.120689 | 2011-12-24 00:50:22 | 2011-09-06 19:09:18 | 
| 59 |   1044 | 49.276867 | -123.120689 | 2011-08-05 12:12:12 | 2011-11-01 00:00:00 | 
| 60 |   1044 | 49.276867 | -123.120689 | 2010-08-05 12:12:12 | 2010-11-01 00:00:00 | 
| 61 |   1044 | 49.276867 | -123.120689 | 2009-08-05 12:12:12 | 2009-11-01 00:00:00 | 
| 62 |   1044 | 49.276867 | -123.120689 | 2008-08-05 12:12:12 | 2008-11-01 00:00:00 | 
| 41 |   1259 | 49.276722 | -123.120735 | 2011-12-08 19:53:39 | 2011-12-07 19:38:02 | 
+----+-----------------+-----------+-------------+---------------------+---------------------+ 

select *,max(created) from user_locations where user_profile_id IN (1044,1259) group by user_profile_id; 

這個查詢是錯誤的,如何才能解決這個問題? 謝謝

回答

1
select u.id,u.user_profile_id,u.latitude,u.longitude,u.modified,u.created 
from user_locations u where u.user_profile_id in(1044,1259) and u.created = 
(select max(g.created) from user_locations g where u.user_profile_id=g.user_profile_id) group by u.user_profile_id; 
+0

它返回所有的結果,沒有工作,THX雖然 – apoo 2012-03-26 21:28:49

+0

你與你的IDS適當替換(1044,1259)?你也使用什麼語言將數據傳遞給mysql – kasavbere 2012-03-26 22:03:21

+0

1044,1259是合適的ID,我直接輸入到mysql客戶端,要確保sql語句是正確的。您的建議會返回user_profile_id = 1044的所有結果 – apoo 2012-03-26 22:06:03