douchen4547 2019-08-02 20:43
浏览 92
已采纳

sql group by user HAVING time ASC ORDER BY time DESC

SQL

$sql = "SELECT DISTINCT from_user, messages.* FROM messages WHERE to_user = :user OR from_user = :usr Group BY from_user 
ORDER BY time DESC"; 

It works but It shows user message from latter , before order by How I could do something like

$sql = "SELECT DISTINCT from_user, messages.* FROM messages WHERE to_user = :user OR from_user = :usr Group BY from_user HAVING time ASC 
ORDER BY time DESC"; 

?

HAVING time ASC ORDER BY time DESC"; ?

I think you guys got me now , how to solve ?

my table structure

enter image description here

I need to select last message from each user by time ASC and than latter order by time DESC I tried with

 $sql = "SELECT DISTINCT from_user, messages.* FROM messages  WHERE to_user = :user OR from_user = :usr ORDER BY time ASC Group BY from_user
ORDER BY time DESC";  

but do not worked

  • 写回答

2条回答 默认 最新

  • drvpv7995 2019-08-02 20:51
    关注

    Your issue is in the having clause. It is use with aggregate function to group your record and check some condition on it. for more info you may find this link.

    For ordering it is only done by order by clause.

    Moreover in your query you are using group by for only 1 field but then message.* will select all fields, which again shows error.

    Kindly see the above link and re-structure your query.

      select m.*
      from messages  m
      where m.time = (select max(m2.time) from messages  m2 where m2.to_user = m.to_user and m2.from_user=m.from_user)  
      and m.to_user = :user OR m.from_user = :usr 
      order by time desc;
    

    Note: You can apply filter as per your need. Variant of this may help in your query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部