【问题标题】:Having clause does not work [duplicate]有子句不起作用[重复]
【发布时间】:2015-04-30 19:35:04
【问题描述】:

我是 SQL 的初学者,我目前正在尝试使用 HAVING CLAUSE 但它不起作用..

我有两张桌子:

  1. 聊天:

  2. tchat_message:

所以我想要用户的最新消息。

首先:我加入表格:`

select user_id, user_message, max(date_message) 
from tchat 
inner join tchat_message on tchat.id=tchat_message.user_id

这里没问题。

第二个:我用了having子句:

select user_id, user_message, max(date_message) 
from tchat 
inner join tchat_message on tchat.id=tchat_message.user_id 
group by user_id 
having max(date_message) = date_message`

这里我有一个错误说:

“有条款”中的未知列“日期消息”

有人有想法吗?

【问题讨论】:

    标签: sql group-by having


    【解决方案1】:

    您错误地使用了having 子句。以下更接近您想要的:

    select tm.user_id, tm.user_message, tm.date_message
    from tchat t inner join
         tchat_message tm
         on t.id = tm.user_id inner join
         (select user_id, max(date_message) as maxdm
          from tchat_message
          group by user_id
         ) tmm
         on tmm.user_id = tm.user_id and tmm.maxdm = tm.date_message;
    

    外部查询中不需要group by。您似乎也不需要 tchat 表(我将其保留以防您在该表中的 select 中有其他列)。

    【讨论】:

    • 没有比这更简单的了吗?
    • @Mr.Smith67 查看重复问题中的其他技术。
    • @GordonLinoff:有时即使您没有从中选择列,也有必要加入表,例如,如果您只想包含在另一个表中匹配的记录。跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-30
    • 2018-08-28
    • 2012-11-30
    • 1970-01-01
    • 2023-02-06
    • 2013-08-03
    • 2016-03-27
    相关资源
    最近更新 更多