开发者

GROUP BY and ORDER BY [duplicate]

开发者 https://www.devze.com 2023-01-24 02:39 出处:网络
This question already has an answer here: Closed 10 years ago. Possible Duplicate: SQL ORDER BY total within GROUP BY
This question already has an answer here: Closed 10 years ago.

Possible Duplicate:

SQL ORDER BY total within GROUP BY

SELECT *
FROM users_pm_in
WHERE uID = '1'
GROUP BY dialog_id
ORDER BY date DESC

Wont work properly. What i want to do is group in to dialog_id.. Then all with the dialog_id sort them by date, and then sort them by date for all..

So:

id | uID | bID | msg     | dialog_id | date
--------------------------------------------------
 1 | 1   | 2   | Hello   | 1         | 1289158631
 2 | 2   | 1   | Hi?     | 1         | 1289158691
 3 | 1   | 2   | Wazzaa? | 1         | 1289158931

The two entry´s of the dialog_id gets 1 (With GROUP BY). OK. And then it should order by the one of the two entrys(inside the group) that have the newest date(order by date desc). Which this case is the one with date 1289158931.

How can this be done?

UPDATE:

What i want to come out:

while($row = mysql_fetch_array($query)){
    echo $row["msg"] // it should echo 开发者_开发技巧"Wazzaa?"
    echo $row["id"] // it should give me id 3
}

It give me the last for each dialog_id, thats why i want it grouped in.


Use:

  SELECT a.id, 
         a.msg
    FROM USERS_PM a
   WHERE a.dialog_id = 1
     AND 1 IN (a.uid, a.bid)
ORDER BY a.date DESC
   LIMIT 1

...or:

SELECT a.id, 
       a.msg
  FROM USERS_PM a
  JOIN (SELECT t.dialog_id,
               MAX(t.date) AS max_date
          FROM USERS_PM t
      GROUP BY t.dialog_id) b ON b.dialog_id = a.dialog_id
                             AND b.max_date = a.date
 WHERE a.dialog_id = 1
   AND 1 IN (a.uid, a.bid)
0

精彩评论

暂无评论...
验证码 换一张
取 消