我在从存储用户之间消息的表中检索数据时遇到问题。这是表格:
CREATE TABLE messages
(
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
sender VARCHAR(20),
recipient VARCHAR(30),
content TEXT,
is_read TINYINT(1),
created_at DATETIME,
PRIMARY KEY (`id`) ,
INDEX idx_sender (sender) ,
INDEX idx_recipient (recipient)
);
INSERT INTO messages (id, sender, recipient, content, is_read, created_at)
VALUES
-- Alice and George
(1, 'Alice', 'George', 'Happy new year', 1, '2012-12-24 23:05:00'),
(2, 'George', 'Alice', 'It is chrimas night...', 1, '2012-12-24 23:10:00'),
(3, 'Alice', 'George', 'Happy Xmas then', 0, '2012-12-25 00:00:00'),
-- John and Paul
(4, 'John', 'Paul', 'Hi Paul', 1, '2012-12-26 09:00:00'),
(5, 'Paul', 'John', 'Hi John', 1, '2012-12-26 09:05:00'),
(6, 'John', 'Paul', 'Have you done this ?', 1, '2012-12-26 09:10:00'),
(7, 'Paul', 'John', 'No I was unpacking my gifts', 0, '2012-12-26 09:05:00'),
-- George and Tim
(8, 'George', 'Tim', 'How was the end of the world ?', 1, '2012-12-22 10:10:00'),
(9, 'Tim', 'George', 'Really nice !', 0, '2012-12-22 10:15:00'),
-- John and Tim
(10, 'John', 'Tim', 'I don\'t know if I should fire you for new year\'s eve', 1, '2012-12-27 15:20:00'),
(11, 'Tim', 'John', 'That is a great idea!', 0, '2012-12-27 15:20:00');
假设 George 和 John 是经理,其他人是员工。我需要检索管理员是收件人的最新未读消息。同时,我必须只检索它们也是对话发起者的那些消息。
所以结果必须是:
- message id 7 : 'Paul', 'John', 'No I was unpacking my gift', 0, 2012-12-26 09:05:00
- 消息 id 9 : 'Tim', 'George', 'Really nice', 0, 2012-12-22 10:15:00
- message id 11 : 'Tim', 'John', 'That is a great idea!', 0, 2012-12-27 15:20:00
我进行了一个查询,几乎就是这样,但是缺少消息 id 11 的行:
SELECT
m.*
FROM
messages m
INNER JOIN (
-- retrieve the first message (fm)
SELECT t.sender, t.recipient
FROM (
SELECT id, sender, recipient, content, created_at,
IF ( sender IN ('John', 'George'), sender, recipient ) AS the_other
FROM messages
WHERE
sender IN ('John', 'George')
OR recipient IN ('John', 'George')
ORDER BY
created_at ASC
) t
GROUP BY
the_other
HAVING t.sender IN ('John', 'George')
) fm ON fm.recipient = m.sender
AND fm.sender = m.recipient
WHERE
m.recipient IN ('John', 'George')
AND m.is_read = 0
ORDER BY
m.created_at DESC
LIMIT 0, 10
缺少消息 id 11,因为子查询按 the_other 分组。如果我按发件人和收件人拆分“分组依据”,它将检索消息 id 3,但它是不需要的行。
解决我的问题的 SQL 应该是什么?