1

我需要一个在第一个表的最大 id 上使用自连接的 sql。请看下面的表格图像。我按 service_id 对表进行分组,但我需要每个组的最后一条消息。因此,对于服务组 5,消息计数应为 3,last_message 应为thirdMsg5。我在下面写了一个sql,其他一切都很好,但是在自加入的情况下会引发错误。它无法识别msgTbl1.last_message_id。我想我是在准备之前打电话给它的。我需要帮助来解决这个问题 在一个查询中解决这个问题的最佳 sql 是什么?如果可能,请以 laravel 查询构建器格式向我提供此查询。

SELECT count(msgTbl1.id) as message_count, 
       max(msgTbl1.id) as last_message_id, 
       msgTbl1.body, 
       msgTbl2.body as last_message, 
       services.name as service_name
FROM messages msgTbl1
LEFT JOIN (SELECT id, body FROM messages) AS msgTbl2 
   ON msgTbl2.id = msgTbl1.last_message_id
LEFT JOIN services on services.id = msgTbl1.service_id 
WHERE receiver_id = 4 AND read_user = 'no'
GROUP BY msgTbl1.service_id

在此处输入图像描述

消息表的sql

CREATE TABLE `messages` (
  `id` int(11) UNSIGNED NOT NULL,
  `sender_id` int(11) UNSIGNED DEFAULT NULL,
  `receiver_id` int(11) UNSIGNED DEFAULT NULL,
  `service_id` int(11) UNSIGNED NOT NULL,
  `sender_type` enum('user','agent','admin') NOT NULL,
  `receiver_type` enum('user','agent','admin') NOT NULL,
  `body` text,
  `files` varchar(500) DEFAULT NULL COMMENT 'serialize',
  `new_notification` enum('no','yes') NOT NULL DEFAULT 'yes',
  `read_user` enum('yes','no') NOT NULL DEFAULT 'no',
  `read_agent` enum('yes','no') NOT NULL DEFAULT 'no',
  `status` enum('active','archive','deleted') NOT NULL DEFAULT 'active',
  `created_at` datetime NOT NULL,
  `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `messages` (`id`, `sender_id`, `receiver_id`, `service_id`, `sender_type`, `receiver_type`, `body`, `files`, `new_notification`, `read_user`, `read_agent`, `status`, `created_at`, `updated_at`) VALUES
(1, 22, 4, 5, 'user', 'agent', 'firstMsg5', NULL, 'yes', 'no', 'yes', 'active', '2016-03-24 00:00:00', '2016-04-12 05:40:28'),
(2, 22, 4, 5, 'user', 'agent', 'secondMsg5', NULL, 'yes', 'no', 'yes', 'active', '2016-03-24 00:00:00', '2016-04-12 05:40:31'),
(3, 22, 4, 9, 'user', 'agent', 'firstMsg9', NULL, 'yes', 'yes', 'yes', 'active', '2016-03-24 00:00:00', '2016-04-12 05:40:45'),
(4, 4, 4, 9, 'agent', 'user', 'secondMsg9', NULL, 'yes', 'yes', 'yes', 'active', '2016-03-24 00:00:00', '2016-04-12 05:40:56'),
(5, 22, 4, 5, 'user', 'agent', 'thirdMsg5', NULL, 'yes', 'yes', 'yes', 'active', '2016-03-24 00:00:00', '2016-04-12 05:41:08');
4

1 回答 1

1

尝试这个:

SELECT message_count, 
       last_message_id, 
       msgTbl1.body,        
       services.name as service_name
FROM messages msgTbl1
INNER JOIN (
   SELECT MAX(id) AS last_message_id, COUNT(*) AS message_count
   FROM messages
   WHERE read_user = 'no'
   GROUP BY service_id) AS msgTbl2 
   ON msgTbl1.id = msgTbl2.last_message_id
LEFT JOIN services on services.id = msgTbl1.service_id 
WHERE receiver_id = 4  
于 2016-04-12T13:01:23.913 回答