MySql:使用GROUP BY和MAX选择最后插入的值

时间:2017-05-18 22:00:17

标签: mysql

我有一个名为message的表,有5列。主键是message_id,它是自动递增的。 enter image description here

我试图通过使用Group By和Max来选择并显示最后插入的消息,其中related_message id为26。
所以我想从表中选择所有内容,只有最后插入的消息是“stackoverflow”。

我尝试使用各种方法但无济于事。

SELECT *
   FROM message
   WHERE person_send_id = :person_send_id OR person_receive_id = :person_receive_id 
   AND related_message IN (SELECT MAX(related_message) FROM message GROUP BY related_message DESC)
   ORDER BY message_id DESC

方法2

SELECT message_id, message, person_send_id, person_receive_id, max(related_message) as `related_message`
   FROM message
   WHERE person_send_id = :person_send_id OR person_receive_id = :person_receive_id
   GROUP BY related_message DESC
   ORDER BY message_id DESC


在DarbyM

的帮助下解决方案
SELECT m1.*
  FROM message m1
  JOIN (SELECT MAX(message_id) AS messageID
        FROM message
        Group By related_message) max
  ON max.messageID = m1.message_id 
  WHERE person_send_id = :person_send_id OR person_receive_id = :person_receive_id 

3 个答案:

答案 0 :(得分:1)

SELECT * FROM message WHERE related_message == 26 and message_id >=(SELECT Max(message_id) FROM message WHERE related_message = 26)

答案 1 :(得分:1)

我相信这就是你所追求的:

SELECT m1.*
FROM message m1
JOIN (SELECT MAX(message_id) AS messageID 
        FROM messages
        Group By related_message) max
    ON max.messageID = m1.message_id
WHERE person_send_id IN (:person_send_id, :person_receive_id )

答案 2 :(得分:1)

第一个建议:

SELECT * FROM message INNER JOIN 
    (SELECT MAX(message_id) AS max_msg_id FROM message WHERE person_send_id = :person_send_id OR person_receive_id = :person_receive_id)
AS aux_table ON aux_table.max_msg_id = message.message_id

第二个建议:

SELECT * FROM message INNER JOIN 
    (SELECT MAX(message_id) AS max_msg_id FROM message WHERE related_msg =: related_msg)
AS aux_table ON aux_table.max_msg_id = message.message_id