· 9 years ago · Jan 01, 2017, 07:48 PM
1CREATE TABLE IF NOT EXISTS `messages` (
2 `id` int(11) NOT NULL,
3 `from` int(11) NOT NULL,
4 `to` int(11) NOT NULL,
5 `text` text NOT NULL,
6 `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
7 `read` enum('0','1') NOT NULL DEFAULT '0'
8) ENGINE=InnoDB DEFAULT CHARSET=utf8
9
10INSERT INTO `messages` (`id`, `from`, `to`, `text`, `date`, `read`) VALUES
11(1, 56, 60, 'xfgvbxfgbfgb', '2014-10-10 10:11:33', '0'),
12(2, 60, 56, ' rtdrtyhdtryjftujfyujyfju', '2014-10-10 11:12:14', '0'),
13(3, 56, 62, 'srtgrtgdrtg', '2014-10-10 21:32:26', '0'),
14(4, 67, 56, 'vdxfvdfvdf', '2014-10-10 22:04:38', '0');
15
16SELECT *
17FROM messages
18WHERE `from` = :id OR `to` = :id
19ORDER BY `date` DESC
20LIMIT 0, 5;
21
22SELECT *
23FROM messages
24WHERE `from` = :id OR `to` = :id
25GROUP BY `from`, `to`
26ORDER BY `date` DESC
27LIMIT 0, 5;
28
29SELECT * FROM (
30 SELECT * FROM (
31 SELECT id, `from` AS inspected_user,
32 `to` AS interlocutor, `date`,
33 `text`, `read`
34 FROM messages AS m1
35 WHERE `from` = :id
36 UNION
37 SELECT id, `to` AS inspected_user,
38 `from` AS interlocutor, `date`,
39 `text`, `read`
40 FROM messages AS m2
41 WHERE `to` = :id
42 ) AS messages
43 ORDER BY `date` DESC -- Ñ Ñ‚ÑƒÐ¿Ð¾Ð¹ и не придумал, как избавитьÑÑ Ð¾Ñ‚ Ñтого
44) AS messages_outer
45GROUP BY `interlocutor`
46ORDER BY `date` DESC
47LIMIT 0, 5;