douchen4547 2019-08-03 04: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-03 04: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条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向