MySQL Query group by获取最后一个id

时间:2012-07-11 07:54:14

标签: php mysql group-by

这是我的表

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 ..

我想和他的朋友一起列出jon的最后消息

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

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

6 个答案:

答案 0 :(得分:4)

使用此:

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,我真的忘记了一些重要的事情:)

答案 1 :(得分: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

答案 2 :(得分: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

答案 3 :(得分:1)

试试这个::

SELECT * 
FROM table 
WHERE sender ='jon' OR receiver='jon' 
GROUP BY msg 
ORDER BY id desc

答案 4 :(得分:0)

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

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

答案 5 :(得分:-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