在 GROUP BY 之前使用 JOIN 进行 ORDER BY

ORDER BY before GROUP BY with JOIN

我的 SQL 查询有问题。我想为用户显示最后一条消息。所以,我使用方法 "GROUP BY" 但他不显示最后一条消息。

这是我的第一个查询:

SELECT `messages`.*, `conversations`.* 
FROM `messages` JOIN `conversations` ON `conversations`.`cNUM` = `messages`.`mCONV_NUM` 
WHERE `cUSER2` = '2' 
GROUP BY `messages`.`mCONV_NUMn`

我尝试关注这个主题:ORDER BY date and time BEFORE GROUP BY name in mysql(以及许多其他主题)

我有这个:

SELECT `messages`.*, `conversations`.* 
FROM (SELECT mTIME 
      FROM `messages` 
      ORDER BY mTIME desc) AS M 
JOIN `conversations` ON `conversations`.`cNUM` = `messages`.`mCONV_NUM` 
WHERE `cUSER2` = '2' 
GROUP BY `messages`.`mCONV_NUMn`

我有这个错误:Table 'messages' 未知。

所以..我需要你们的帮助

您为您的消息 table 指定了一个别名 M,正如 isaace 所说,您在查询的其余部分将其称为 'M',因为这个临时名称在整个查询期间都有效query 和 FROM 是查询处理的初始阶段.

We are talking about something called logical query processing, this means that in your query FROM statement is evaluated and processed initially and then the rest of query.


在 LQP 术语中,查询将按以下顺序处理。

  • FROM --> WHERE --> GROUP BY --> HAVING --> SELECT --> ORDER BY

(当然我遗漏了一些阶段,但你明白了)

您还可以使用 LIMIT 获取用户的最后一条消息。 只需在末尾添加 LIMIT 1。

你说你想要一个用户的最后一条消息,但看起来你真的想要多条消息,即他们参与的每个对话的最后一条消息。

由于 MySQL 中缺少 CROSS APPLY 和 window 函数,您需要一个查询来进行大量查找以获取每个对话的最后一条消息:

select *
from conversations c 
join messages m on m.mconv_num = c.cnum
where c.cuser2 = 2
and not exists 
(
  select * 
  from messages m2 
  where m2.mconv_num = m.mconv_num
  and m2.mtime > m.mtime
);

I want to display the last message for a user.

您收到了 LIMIT 用户的最后一条消息:

select *
from conversations c 
join messages m on m.mconv_num = c.cnum
where c.cuser2 = 2
order by m.mtime
limit 1;