MySQL:这个版本的MySQL还不支持'LIMIT& IN / ALL / ANY / SOME子查询

时间:2016-05-25 17:03:16

标签: mysql sql

我尝试在左连接条件中使用在子查询限制但我收到sql错误。

这是我的SQL查询:

enableRowHashing:false

表格结构:

MessageThreads

SELECT * FROM `MessageThreads`
LEFT JOIN `users` ON `users`.`id` in 
  (select SenderId from Messages where 
     Messages.MessageThreadId =  MessageThreads.MessageThreadId 
     order by Messages.MessageId desc limit 1)

用户

----------------------
|    MessageThreadId  |  
----------------------

讯息

----------------------
|   id    |   name   |
----------------------

我的目的:我想获取所有MessageThreads,其中包含在Messages表中收到的最新消息的用户详细信息。

这可能以这种方式实现,或者最佳方法是什么?

我真的很感激任何贡献。

由于

2 个答案:

答案 0 :(得分:2)

选择最大(id)

SELECT * FROM `MessageThreads`
LEFT JOIN `users` ON `users`.`id` = 
   (select SenderId from Messages where 
        Messages.MessageThreadId =  MessageThreads.MessageThreadId 
        and Messages.MessageId = (select max(Messages.MessageId) from Messages));

答案 1 :(得分:1)

试试这个:

SELECT mt.*, u.* 
FROM MessageThreads AS mt
LEFT JOIN (
   SELECT MessageThreadId, MAX(MessageId) AS MessageId
   FROM Messages
   GROUP BY MessageThreadId
) AS m ON mt.MessageThreadId = m.MessageThreadId
JOIN Messages AS m2 ON m2.MessageId = m.MessageId
JOIN Users AS u ON u.Id = m2.SenderId

此查询将选择与每个消息线程的最新消息相关的用户。