开发者

GROUP BY ORDER BY Help

开发者 https://www.devze.com 2023-02-27 07:30 出处:网络
The following code works, but I want the groups to show their latest query by datetime not the first datetime query. I\'ve tried changing around the ORDER BY from ASC/DESC, but that just changes the o

The following code works, but I want the groups to show their latest query by datetime not the first datetime query. I've tried changing around the ORDER BY from ASC/DESC, but that just changes the order of all the groups, not the data within the groups. I need for both all the inside data of the groups and all the groups to order by the latest datetime.

$query="SELECT * FROM emails 
        WHERE sentto='$sid' 
        GROUP BY sentto 
        ORDER BY datetime DESC LIMIT $eu, $limit ";

Instead of it showing groups and ordering them by the first query:

Message from Sam Richards on January 22, 2011 (this is a group)

Message from John Smith on January 5, 2011 (this is a group)

I want it to show groups and order them by the latest query:

Message from John Smith on April 19, 2011 (this is a group)

Message from Sam Richards on March 10, 2011 (this is a group)

P开发者_Python百科lease help.


I think part of your problem is that you are selecting non-aggregate columns with a group-by query. You should be explicit about which values you want it to return in the aggregate query result.

SELECT sentto, MAX(datetime) AS datetime FROM emails
  GROUP BY sentto
  ORDER BY datetime desc LIMIT $eu, $limit;

I'm still not sure that this gives you what you want. It sounds like you want to actually retrieve the rows for each individual email and just use the GROUP BY maximum for sorting. To do that, you'd probably need to do the above query, then go back and do a second query for each sentto. I can't think of a way offhand to do it in a single query.

SELECT * FROM emails
  WHERE sentto=$sid
  ORDER BY datetime DESC;

(For each sentto returned in the first query.)


How about:

ORDER BY sentto ASC, datetime DESC


To sort the data with in the groups you need to include sentto in the ORDER BY clause.

Try this:

SELECT * FROM emails 
            WHERE sentto='$sid' 
            GROUP BY sentto 
            ORDER BY sentto, datetime DESC LIMIT $eu, $limit 
0

精彩评论

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