2

这是我的桌子

id | sender | receiver | msg  
-----------------------------
1  | jon    | jack     | buzz ...  
2  | jack   | jon      | ?  
3  | adel   | jon      | met me soon  
4  | jon    | adel     | okay  
5  | alex   | jon      | where ar u ?  
6  | jon    | adel     | okay  
7  | adel   | alex     | don't forget the party  
8  | jon    | jack     | may i borrow ur car 
9  | alex   | adel     | of course
10 | jack   | jon      | ok
11 | jack   | jon      | watch the gas
12 | alex   | jon      | i'm dying here
13 | jon    | alex     | 5 mnt ..

我想和他的朋友这样得到乔恩的最后一条消息

id | sender | receiver | msg
-------------------------------------------
13 | jon    | alex     | 5 mnt ..
11 | jack   | jon      | watch the gas
6  | jon    | adel     | okay

如何查询,以获得该结果?

4

6 回答 6

6

用这个:

SELECT *
FROM table
WHERE id IN (
    SELECT MAX(id)
    FROM table
    WHERE sender = 'jon' 
       OR receiver = 'jon'
    GROUP BY IF(sender = "jon", receiver, sender)
) 
ORDER BY id DESC;

编辑:感谢您的编辑 ypercube,我真的忘记了一些重要的事情 :)

于 2012-07-11T07:58:51.753 回答
3

这将返回您想要的内容:

SELECT * FROM 
(SELECT * FROM `table` WHERE sender="jon" OR receiver="jon" ORDER BY id DESC) a 
GROUP BY IF(sender = "jon", receiver, sender) 
ORDER BY id DESC

抱歉第一次回答错了,我想我没有仔细阅读问题。:(

这是测试:

http://sqlfiddle.com/#!2/e66ac/2

于 2012-07-11T07:56:00.120 回答
2
SELECT * FROM 
(SELECT * FROM tblA WHERE sender="jon" OR receiver="jon" ORDER BY id DESC) a 
GROUP BY IF(sender = "jon", receiver, sender) 

请参考http://sqlfiddle.com/#!2/44099/1

于 2012-07-11T08:13:57.890 回答
1

尝试这个::

SELECT * 
FROM table 
WHERE sender ='jon' OR receiver='jon' 
GROUP BY msg 
ORDER BY id desc
于 2012-07-11T07:56:14.273 回答
0

我认为你需要这样的东西:

SELECT * FROM my_table WHERE sender="jon" OR receiver="jon" ORDER BY id DESC

于 2012-07-11T07:58:05.183 回答
-1

这是一个简单的查询,您可以根据自己的逻辑进行更改

SELECT * FROM tbl_enquiry WHERE id IN (
  SELECT Max(id) FROM tbl_enquiry WHERE date = '06/25/2015' GROUP BY cust_id 
) LIMIT 0 , 30
于 2015-06-26T07:23:11.290 回答