MYSQL按顺序和分组依据

时间:2012-08-22 20:08:36

标签: php mysql

我目前有这个

SELECT type, extra_id, COUNT(*) AS count, id 
FROM `notifications` 
WHERE `receiver_id` = '".$this->user_id."' 
    AND `read` = '0' 
GROUP BY type, extra_id 
ORDER BY `id` DESC

但是这只是按照数据库中第一个找到的结果排序,就像我在SELECT id时所做的那样。我如何才能这样做,以便notifications中最后找到的ID在SELECT id 中使用?

1 个答案:

答案 0 :(得分:3)

只需选择MAX(id)代替id

SELECT type, extra_id, COUNT(*) AS count, MAX(id) AS max_id
FROM `notifications` 
WHERE `receiver_id` = '".$this->user_id."' 
    AND `read` = '0' 
GROUP BY type, extra_id 
ORDER BY max_id DESC