1

I have messages from user id 1(5), 2(1), 3(1). (parenthesis show the number of messages for each user id)

Hi here is my code:

$stmt = $dbh->prepare("SELECT * FROM messages WHERE user_id = :user_id ORDER BY id DESC");

i have messages for user id 1, 2, and 3. but for users that have multiple messages like user id 1, I want to only select the latest message from user id 1 and NOT all five messages and i want to select the latest messages from user id 2 and 3. how can i do that? thanks.

baileyJchoi
  • 473
  • 5
  • 17
  • I think, if I'm not mistaken, you still want to select all users at the same time and keep only the last message for each one. Is that so? In that case your answer is already in this question: http://stackoverflow.com/questions/1313120/retrieving-the-last-record-in-each-group – Zeke Mar 25 '17 at 01:35

1 Answers1

1

Adding "LIMIT 1" to your query will do the trick, I believe.

$stmt = $dbh->prepare("SELECT * FROM messages WHERE user_id = :user_id ORDER BY id DESC LIMIT 1");
marmeladze
  • 6,468
  • 3
  • 24
  • 45