MySQL Group,Join和Select Max

时间:2012-06-26 15:36:50

标签: mysql join group-by max

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

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

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

此查询显示了我需要的内容(我猜),除了它提供了来自消息表的最低值。

我该怎么做?我在哪里做错了?

谢谢,

2 个答案:

答案 0 :(得分: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;

解析这个,结果是“使用where;使用索引”,意思是“完成任务”。

答案 1 :(得分: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