关注以下帖子:Get last row PER Group
假设您以用户身份登录:1我希望每个已发送的消息中有一行尚未收到对话组中的响应(实际上,对话只有1条消息)。对于我想要获得的每个对话,对话的“主题”,ToUser和DateTime
任何帮助都会受到欢迎,关于这个主题的最后一个问题对我来说非常宝贵,我非常感谢。
CREATE TABLE messages (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
FromID INT NOT NULL,
ToID INT NOT NULL,
ConversationID INT NOT NULL,
Message varchar(255),
DateTime DATETIME
) ENGINE=InnoDB;
CREATE TABLE conversations (
ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
Subject varchar(255)
) ENGINE=InnoDB;
INSERT INTO conversations (ID, Subject) VALUES (1, "hey"), (2, "hey2"), (3, "hey3");
INSERT INTO messages (FromID, ToID, ConversationID, Message, DateTime) VALUES (1,2, 1, "Hi", "This is a test message", "2010-08-08 16:23:48");
INSERT INTO messages (FromID, ToID, ConversationID, Message, DateTime) VALUES (1,2, 1, "", "Hey again you have not answered", "2010-08-08 16:23:52");
INSERT INTO messages (FromID, ToID, ConversationID, Message, DateTime) VALUES (2,1, 1, "", "Hi this is my answer", "2010-08-08 16:23:59");
INSERT INTO messages (FromID, ToID, ConversationID, Message, DateTime) VALUES (2,1, 2, "2.Hi", "2.This is a test message", "2010-08-08 16:25:48");
INSERT INTO messages (FromID, ToID, ConversationID, Message, DateTime) VALUES (1,2, 2, "", "2.Hi back", "2010-08-08 16:25:52");
INSERT INTO messages (FromID, ToID, ConversationID, Message, DateTime) VALUES (2,1, 2, "", "2.Hi this is my answer", "2010-08-08 16:25:59");
INSERT INTO messages (FromID, ToID, ConversationID, Message, DateTime) VALUES (2,1, 3, "3.Hi", "3.This is a test message", "2010-08-08 16:27:48");
INSERT INTO messages (FromID, ToID, ConversationID, Message, DateTime) VALUES (1,2, 3, "", "2.Hi back", "2010-08-08 16:27:52");
INSERT INTO messages (FromID, ToID, ConversationID, Message, DateTime) VALUES (1,2, 3, "", "2.Hello are you there?", "2010-08-08 16:27:59");
答案 0 :(得分:1)
如果我理解你在寻找什么,我相信这个问题会让你得到你想要的东西:
SELECT `Subject`, `ToID`, `DateTime`, COUNT(*) AS `NumberOfMessagesInConversation`
FROM `messages`
GROUP BY `ConversationID`
HAVING `NumberOfMessagesInConversation` = 1
编辑:此查询应该可以为您提供相同的功能,但在您进行大量对话时可能会更有效:
SELECT `Subject`, `ToID`, `DateTime`
FROM
(
SELECT `ConversationID`, COUNT(*) AS `NumberOfMessagesInConversation`
FROM `messages`
GROUP BY `ConversationID`
HAVING `NumberOfMessagesInConversation` = 1
) AS `message_counts`
JOIN `messages` ON `messages`.`ConversationID` = `message_counts`.`ConversationID`