我有一个PHP脚本,它从数据库中检索消息,然后以收件箱样式的方式显示它们,每条消息一行。每条消息都是2个用户之间对话的一部分。现在,问题是它在输出中为对话中的每条消息返回1条新消息。
如果这有道理?以下是查询的代码:
$sql_select_messages = $db->query( ... );
参数是以下查询字符串:
SELECT m.admin_message, a.name, u.username AS sender_username,
m.* FROM " . DB_PREFIX . "messaging m
LEFT JOIN " . DB_PREFIX . "items a ON a.items_id=m.items_id
LEFT JOIN " . DB_PREFIX . "users u ON u.user_id=m.sender_id
WHERE m.receiver_id='" . $session->value('user_id') . "' AND m.receiver_deleted=0" .
(($page == 'summary') ? " AND m.is_read=0" : '') . "
ORDER BY " . $order_field . " " . $order_type . " LIMIT " . $start . ", " . $limit
部分:
m.* FROM " . DB_PREFIX . "messaging m
从mySQL行中选择包含
等列的数据topic_id
和
message_id
我正在尝试做的是让上面的mySQL查询返回每个topic_id只返回ONE(1)结果(因为可能有几个具有相同数字的topic_id)并且只与最新的(最高数字) message_id。
所以基本上如果有:
================
topic_id | message_id
================
15 10
15 11
15 12
19 02
19 03
19 04
我只希望mySQL返回15/12和19/04。我将如何使用上面的mySQL select查询来完成这项工作?
非常感谢:)
答案 0 :(得分:0)
您需要按两列排序,并对这些列进行分组。
将以下脚本附加到SQL。
GROUP BY topic_id
ORDER BY topic_id DESC, message_id DESC
希望这有帮助。
答案 1 :(得分:0)
您的查询可能如下所示
SELECT m.admin_message, a.name, u.username sender_username, m.*
FROM
(
SELECT MAX(message_id) message_id
FROM messaging
WHERE ... -- < all your where conditions go here
GROUP BY topic_id
) q JOIN messaging m ON q.message_id = m.message_id LEFT JOIN items a
ON a.items_id = m.items_id LEFT JOIN users u
ON u.user_id = m.sender_id
ORDER BY ...
LIMIT ...
这是 SQLFiddle 演示
现在在php方面它看起来像
$sql = "SELECT m.admin_message, a.name, u.username sender_username, m.*
FROM
(
SELECT MAX(message_id)
FROM " . DB_PREFIX . "messaging
WHERE m.receiver_id = '" . $session->value('user_id') . "' AND m.receiver_deleted = 0 " .
(($page == 'summary') ? " AND m.is_read = 0" : '') . "
GROUP BY topic_id
) q JOIN " . DB_PREFIX . "messaging m ON q.message_id = m.message_id LEFT JOIN " . DB_PREFIX . "items a
ON a.items_id = m.items_id LEFT JOIN " . DB_PREFIX . "users u
ON u.user_id = m.sender_id
ORDER BY " . $order_field . " " . $order_type . " LIMIT " . $start . ", " . $limit;
$sql_select_messages = $db->query($sql);
答案 2 :(得分:0)
简单地:
SELECT topic_id, MAX(message_id)
FROM test
GROUP BY topic_id