我需要在两列之后对MySQL表进行排序,但不像常规排序。在聊天应用程序中,我希望获得按时间戳字段排序的结果,但也按发件人
分组CREATE TABLE messages (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
sender int(10) unsigned NOT NULL,
message char(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
INSERT INTO messages VALUES ('1', '2011-02-28 01:58:24', '3', '1');
INSERT INTO messages VALUES ('2', '2011-02-28 01:58:28', '3', '2');
INSERT INTO messages VALUES ('3', '2011-02-28 01:58:35', '1', '5');
INSERT INTO messages VALUES ('4', '2011-02-28 01:58:36', '2', '7');
INSERT INTO messages VALUES ('5', '2011-02-28 01:58:38', '3', '3');
INSERT INTO messages VALUES ('6', '2011-02-28 01:58:39', '2', '8');
INSERT INTO messages VALUES ('7', '2011-02-28 01:58:40', '1', '6');
INSERT INTO messages VALUES ('8', '2011-02-28 01:58:41', '3', '4');
所以:
ORDER BY时间戳,发件人无用
ORDER BY发件人,时间戳非常好,但不会先显示旧邮件
SELECT timestamp, sender, message FROM messages ORDER BY sender IN (SELECT DISTINCT sender FROM messages ORDER BY timestamp), timestamp;
不起作用,因为我认为它必须工作。以下是我对此查询的期望(ofc不是我从此查询得到的结果:P):
+---------------------+--------+---------+
| timestamp | sender | message |
+---------------------+--------+---------+
| 2011-02-28 01:58:24 | 3 | 1 |
| 2011-02-28 01:58:28 | 3 | 2 |
| 2011-02-28 01:58:38 | 3 | 3 |
| 2011-02-28 01:58:41 | 3 | 4 |
| 2011-02-28 01:58:35 | 1 | 5 |
| 2011-02-28 01:58:40 | 1 | 6 |
| 2011-02-28 01:58:36 | 2 | 7 |
| 2011-02-28 01:58:39 | 2 | 8 |
+---------------------+--------+---------+
有什么想法吗?链接?提示?什么? 在此先感谢,欢迎提出任何问题
答案 0 :(得分:1)
它适用于你ORDER BY sender asc, timestamp desc
吗?
<强>更新强>
你可能需要这样的东西:
SELECT a.timestamp, a.sender, a.message
FROM messages a
INNER JOIN
(SELECT b.sender_id, MIN(b.timestamp) as timestamp
FROM messages b GROUP BY sender
)c ON (c.sender = a.sender)
ORDER BY c.timestamp, a.sender
答案 1 :(得分:0)
SELECT * FROM messages ORDER BY sender, timestamp ASC;
将按发件人排序,然后按时间戳为您提供按时间戳排序的每个发件人数据。在MySQL中,当你使用多种排序时,它只能按一种排序,然后另一种排序。
你想要实现的是......好吧,不可能,你不能将发件人分组,如果他们不符合发送者的想法......我给的是你在MySQL中最接近的