我有一张表格如下:
id | sender | receiver | time
1 | felix@a.com | lea@a.com | 2014-07-04 22:50:16
2 | felix@a.com | lea@a.com | 2014-07-04 22:51:20
3 | felix@a.com | mia@a.com | 2014-07-04 22:51:41
4 | mia@a.com | felix@a.com | 2014-07-04 22:52:45
5 | mia@a.com | felix@a.com | 2014-07-04 22:52:58
6 | lea@a.com | felix@a.com | 2014-07-04 22:53:33
7 | felix@a.com | mia@a.com | 2014-07-04 22:55:53
我希望获得一个不同的发件人/收件人,其中包含一个条目&f; felix @ a.com'按时间排序。所以,输出将如下所示
id | sender | receiver | time
6 | lea@a.com | felix@a.com | 2014-07-04 22:53:33
7 | felix@a.com | mia@a.com | 2014-07-04 22:55:53
我正在尝试这个但不能正常工作
SELECT *
FROM (
SELECT *
FROM `message`
ORDER BY `time` DESC
) AS `message`
WHERE (
message.sender = 'felix@a.com'
OR message.receiver = 'felix@a.com'
)
GROUP BY message.receiver, message.sender
请指导我实现目标的正确方法。
答案 0 :(得分:1)
DROP TABLE my_table;
CREATE TABLE my_table
(id INT NOT NULL PRIMARY KEY
,sender VARCHAR(20) NOT NULL
,receiver VARCHAR(20) NOT NULL
,time DATETIME NOT NULL
);
INSERT INTO my_table VALUES
(1,'felix@a.com','lea@a.com','2014-07-04 22:50:16'),
(2,'felix@a.com','lea@a.com','2014-07-04 22:51:20'),
(3,'felix@a.com','mia@a.com','2014-07-04 22:51:41'),
(4,'mia@a.com','felix@a.com','2014-07-04 22:52:45'),
(5,'mia@a.com','felix@a.com','2014-07-04 22:52:58'),
(6,'lea@a.com','felix@a.com','2014-07-04 22:53:33'),
(7,'felix@a.com','mia@a.com','2014-07-04 22:55:53');
(SELECT * FROM my_table WHERE sender = 'felix@a.com' ORDER BY time DESC LIMIT 1)
UNION
(SELECT * FROM my_table WHERE receiver = 'felix@a.com' ORDER BY time DESC LIMIT 1);
+----+-------------+-------------+---------------------+
| id | sender | receiver | time |
+----+-------------+-------------+---------------------+
| 7 | felix@a.com | mia@a.com | 2014-07-04 22:55:53 |
| 6 | lea@a.com | felix@a.com | 2014-07-04 22:53:33 |
+----+-------------+-------------+---------------------+
答案 1 :(得分:0)
SELECT DISTINCT sender, receiver
FROM tablename ORDER BY time DESC;
此SQL DISTINCT子句示例将返回每个唯一的发送方和接收方组合。在这种情况下,DISTINCT适用于DISTINCT关键字后面列出的每个字段。