如何将mysql结果分组
我在mysql中有下表如何将mysql结果分组,mysql,group-by,sql-order-by,Mysql,Group By,Sql Order By,我在mysql中有下表 +-----------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------------+-------------+------+-----+---------+----------------+ | id
+-----------------+-------------+------+-----+---------+----------------+
| 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 | |
+-----------------+-------------+------+-----+---------+----------------+
我想做一个查询,在那里我传递一个用户配置文件id列表,然后我得到他们的最新记录。每个用户\u配置文件\u 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 |
+----+-----------------+-----------+-------------+---------------------+---------------------+
例如:
此查询错误,如何修复此问题?
谢谢您是否用合适的ID替换了10441259?另外,您使用什么语言将数据传递到MySQL10441259是合适的ID,我直接在mysql客户端中键入,首先要确保sql语句是正确的。您的建议将返回用户_profile_id=1044;的所有结果。我已为您编辑了代码段,请尝试再次复制和粘贴。我在一个类似的表上测试了它,代码运行正常!这就完成了任务:选择u.id、u.user_profile_id、u.latitude、u.modified、u.created from user_locations u其中u.user_profile_id在10441259中,u.created=选择maxg.created from user_locations g其中u.user_profile_id=g.user_profile_id组由u.user_profile_id创建;
select *,max(created) from user_locations where user_profile_id IN (1044,1259) group by user_profile_id;
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;