Как я могу подгруппировать мои результаты MySQL - PullRequest
0 голосов
/ 27 марта 2012

У меня есть следующая таблица в 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 и получаю их последнюю запись обратно. Каждый 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 Ответ

1 голос
/ 27 марта 2012
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;
...