按最大日期选择account_id

时间:2015-09-04 04:40:15

标签: php mysql database

您好我有以下表格设计

ID       account_id       score     date
------------------------------------------    
1       500             4               x
2       764             4               x
3       500             6               x
4       500             7               x
5       764             5               x

我正在尝试使用最新的account_id条目获取所有

所以我的代码应该返回

ID       account_id       score     date
------------------------------------------    
4       500             7               x
5       764             5               x

我尝试了以下代码,但它似乎返回了第一个条目但是使用了最新日期

SELECT account_id,score, max(date) from table group by account_id

5 个答案:

答案 0 :(得分:0)

试一试 -

SELECT distinct a.id,a.account_id,b.score,b.date 
FROM mytable b 
JOIN 
(
SELECT account_id,MAX(id) AS id 
FROM mytable 
GROUP BY account_id
) a ON a.account_id=b.account_id
ORDER BY a.id;

答案 1 :(得分:0)

案例1:如果id是自动增量列,则max(id)表示最新行。

select * from
(select * from table_name
order by id desc) temp
group by account_id 

案例2:如果date列决定最新行,则将id替换为dateorder clause中的group clause

答案 2 :(得分:0)

这个问题只是SQL Select only rows with Max Value on a Column

的重复

你会找到一个很好的解释。

答案 3 :(得分:0)

SELECT a.* 
FROM table a
INNER JOIN (
  SELECT `account_id`,MAX(`date`) AS latest FROM table GROUP BY account_id 
) b
ON a.`date` = b.`latest` AND a.`account_id` = b.`account_id`
ORDER BY `date` DESC

参考:

Using ORDER BY and GROUP BY together

答案 4 :(得分:0)

尝试使用此查询可以正常使用

Select a.account_id,a.score,a.date
from authors as a
join
(Select account_id,max(date) as date
from authors
group by account_id) as d
on(d.date=a.date)