1

首先,我知道这里有人问过类似的问题,我已经检查过,但找不到合适的解决方案来解决我的问题。

我有这两个表(为简单起见,只修剪所需的部分):

CREATE TABLE messages(
message_id MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
message_conversation_id MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0', 
message_from MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
message_to MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
message_text TEXT NOT NULL DEFAULT '',
PRIMARY KEY (message_id),
KEY message_conversation_id (message_conversation_id),
KEY message_from (message_from),
KEY message_to (message_to)
) ENGINE=INNODB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

CREATE TABLE users (
user_id MEDIUMINT(8) UNSIGNED NOT NULL AUTO_INCREMENT,
user_name VARCHAR(400) NOT NULL DEFAULT '', 
PRIMARY KEY (user_id)
) ENGINE=INNODB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

我想做一个查询,显示最大 message_id 的 message_text 和用户信息(可能都存储在 message_from 或 message_to 中,并使用 where 子句过滤(简单地说:消息会来找我,并向我提供其他用户的用户信息,因为在那次对话中,最后一条消息可能来自我或对话中的其他人)(这让我坚持解决问题))。

这个查询是我到目前为止提出的:

SELECT `m`.*, `u`.*, `u2`.*
FROM (`messages` AS m)
INNER JOIN `users` AS u ON `u`.`user_id`=`m`.`message_from`
INNER JOIN `users` AS u2 ON `u2`.`user_id`=`m`.`message_to`
WHERE (m.message_from="1" OR m.message_to="1")
AND `u`.`user_id` != '1'
AND `u2`.`user_id` != '1'
GROUP BY `m`.`message_conversation_id`
ORDER BY `m`.`message_id` desc

这个查询准确地显示了我需要的东西(我猜),除了它提供消息表中的最低值。

我怎样才能做到这一点 ?我在哪里做错了?

谢谢,

4

2 回答 2

2

这是获取每个对话的最新消息的另一种方法。

SELECT m.*, u.*, u2.*
FROM (`messages` AS m)
LEFT JOIN users AS u ON u.user_id=m.message_from
LEFT JOIN users AS u2 ON u2.user_id=m.message_to
WHERE (m.`message_from` != 1 AND m.`message_to` != 1) AND m.`message_id` IN (
    SELECT MAX(`message_id`) 
    FROM `messages` 
    GROUP BY `message_conversation_id` 
    HAVING `message_id` = m.`message_id`)
ORDER BY m.message_id DESC;

解释一下,结果是“Using where; Using index”,意思是“任务完成”。

于 2012-06-26T18:14:42.320 回答
0

我得到了我需要的东西,我需要的是 message_body 结果列。这是健康的,还是有其他(可能更好)的方法?

SELECT DISTINCT(m.message_conversation_id),max(m.message_id), m.*,u.*, u2.*, 
(SELECT m2.message_text FROM messages m2 WHERE m2.message_id = max(m.message_id)) AS 'message_body'
FROM (`messages` AS m)
LEFT JOIN users AS u ON u.user_id=m.message_from
LEFT JOIN users AS u2 ON u2.user_id=m.message_to
WHERE (m.message_from='1' OR m.message_to='1')
GROUP BY m.message_conversation_id
ORDER BY m.message_id DESC
于 2012-06-26T17:18:44.557 回答