2014-07-07 33 views
0

我有一個表,如下所示:MySQL的複雜的查詢需要建議

id | sender  | receiver | time 
    1 | [email protected] | [email protected] | 2014-07-04 22:50:16  
    2 | [email protected] | [email protected] | 2014-07-04 22:51:20  
    3 | [email protected] | [email protected] | 2014-07-04 22:51:41  
    4 | [email protected] | [email protected] | 2014-07-04 22:52:45  
    5 | [email protected] | [email protected] | 2014-07-04 22:52:58 
    6 | [email protected] | [email protected] | 2014-07-04 22:53:33 
    7 | [email protected] | [email protected] | 2014-07-04 22:55:53 

我想不同的發送器/接收器具有按時間倒序用「[email protected]」爲了一個條目。因此,輸出會像下面

id | sender  | receiver | time 
    6 | [email protected] | [email protected] | 2014-07-04 22:53:33 
    7 | [email protected] | [email protected] | 2014-07-04 22:55:53 

我這個努力,但工作不正常

SELECT * 
FROM (
SELECT * 
FROM `message` 
ORDER BY `time` DESC 
) AS `message` 
WHERE (
message.sender = '[email protected]' 
OR message.receiver = '[email protected]' 
) 
GROUP BY message.receiver, message.sender 

請指引我正確的方式來實現我的目標。

+0

所以你想要最近一行where sender = felix和最近一行接收者是felix?你可以用UNION來做到這一點。 – Strawberry

回答

0
SELECT DISTINCT sender, receiver 
FROM tablename ORDER BY time DESC; 

此SQL DISTINCT子句示例將返回每個唯一的發件人和收件人組合。在這種情況下,DISTINCT適用於DISTINCT關鍵字後面列出的每個字段。

+0

謝謝,但這不是給我想要的輸出 – Kabir

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,'[email protected]','[email protected]','2014-07-04 22:50:16'), 
(2,'[email protected]','[email protected]','2014-07-04 22:51:20'), 
(3,'[email protected]','[email protected]','2014-07-04 22:51:41'), 
(4,'[email protected]','[email protected]','2014-07-04 22:52:45'), 
(5,'[email protected]','[email protected]','2014-07-04 22:52:58'), 
(6,'[email protected]','[email protected]','2014-07-04 22:53:33'), 
(7,'[email protected]','[email protected]','2014-07-04 22:55:53'); 

(SELECT * FROM my_table WHERE sender = '[email protected]' ORDER BY time DESC LIMIT 1) 
UNION 
(SELECT * FROM my_table WHERE receiver = '[email protected]' ORDER BY time DESC LIMIT 1); 
+----+-------------+-------------+---------------------+ 
| id | sender  | receiver | time    | 
+----+-------------+-------------+---------------------+ 
| 7 | [email protected] | [email protected] | 2014-07-04 22:55:53 | 
| 6 | [email protected] | [email protected] | 2014-07-04 22:53:33 | 
+----+-------------+-------------+---------------------+ 
+0

謝謝@Strawberry,它只會用於以上輸入。 '[email protected]'發送或接收來自或來自許多用戶的信息時發生了什麼? – Kabir

+0

如果問題發生變化,那麼答案可能也是如此。 – Strawberry