我有一個包含用戶到用戶消息的表。對話具有兩個用戶之間的所有消息。我正在嘗試獲取所有不同會話的列表,並只顯示列表中發送的最後一條消息。SQL中替代子查詢的替代方法
我可以用FROM中的SQL子查詢來做到這一點。
CREATE TABLE `messages` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`from_user_id` bigint(20) DEFAULT NULL,
`to_user_id` bigint(20) DEFAULT NULL,
`type` smallint(6) NOT NULL,
`is_read` tinyint(1) NOT NULL,
`is_deleted` tinyint(1) NOT NULL,
`text` longtext COLLATE utf8_unicode_ci NOT NULL,
`heading` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at_utc` datetime DEFAULT NULL,
`read_at_utc` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
SELECT * FROM
(SELECT * FROM `messages` WHERE TYPE = 1 AND
(from_user_id = 22 OR to_user_id = 22)
ORDER BY created_at_utc DESC
) tb
GROUP BY from_user_id, to_user_id;
SQL小提琴:
http://www.sqlfiddle.com/#!2/845275/2
有沒有辦法做到這一點沒有一個子查詢?
(寫DQL僅支持在「IN」的子查詢)
不,這需要一個子查詢。 –
子查詢有什麼問題? – JohnFx