Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用mysql从一个选项卡中为每个组检索一项_Mysql_Sql - Fatal编程技术网

使用mysql从一个选项卡中为每个组检索一项

使用mysql从一个选项卡中为每个组检索一项,mysql,sql,Mysql,Sql,我有一个表格,上面有来自不同用户的推文,我想从中选择每个人的最新推文。我应该使用什么sql来检索这些数据 twitter_username tweet date stevdobb tweet one 2013-06-07 12:00 stevdobb tweet two 2013-06-09 12:00 stevdobb tweet three 2013-06-05 12:00 other_username

我有一个表格,上面有来自不同用户的推文,我想从中选择每个人的最新推文。我应该使用什么sql来检索这些数据

twitter_username   tweet       date
stevdobb           tweet one   2013-06-07 12:00
stevdobb           tweet two   2013-06-09 12:00   
stevdobb           tweet three 2013-06-05 12:00
other_username     tweet four  2013-06-10 12:00
试一试


GROUP BY通常与聚合函数一起使用,但如果没有聚合函数,则只显示第一条匹配记录。如果您按日期描述订购,则它是最新的。

您可以通过创建子查询来按用户查找最新的日期

select twitter_username, max(date) from tweets group by twitter_username
然后可以使用此子查询获取所需的tweet

select tweets.* from tweets join ( 
   select twitter_username, max(date) max_date 
   from tweets group by twitter_username
) latest on 
latest.twitter_username = tweets.twitter_username and 
latest.max_date = tweets.date

这将返回每个用户的所有推文。我只想要每个用户的最后一条tweet。
select tweets.* from tweets join ( 
   select twitter_username, max(date) max_date 
   from tweets group by twitter_username
) latest on 
latest.twitter_username = tweets.twitter_username and 
latest.max_date = tweets.date