0

I would like to select only unique row from the table, can someone help me out?

 SELECT * FROM table
 where to_user = ? 
 and deleted != ? 
 and del2 != ?
 and is_read = '0' 
  order by id desc


+----+-----+------+
| id | message_id |
+----+-----+------+
|  1 | 23         | 
|  2 | 23         | 
|  3 | 23         | 
|  4 | 24         | 
|  5 | 25         | 
+----+-----+------+

I need something like

+----+-----+------+
| id | message_id |
+----+-----+------+
|  3 | 23         | 
|  4 | 24         | 
|  5 | 25         | 
+----+-----+------+
3
  • So you only need the largest id for a particular message_id? Commented Nov 27, 2013 at 6:59
  • @SWeko if the message_id is similar I just want only the last one. Commented Nov 27, 2013 at 7:02
  • If by similar you mean same, and the last one is the largest one, then mine or Aziz's answers will do the trick. Commented Nov 27, 2013 at 7:04

3 Answers 3

4

Try this:

SELECT MAX(id), message_id
FROM tablename
GROUP BY message_id

and if you have other fields then:

SELECT MAX(id), message_id
FROM tablename
WHERE to_user = ? 
AND deleted != ? 
AND del2 != ?
AND is_read = '0'
GROUP BY message_id 
ORDER BY id DESC
Sign up to request clarification or add additional context in comments.

Comments

1

If you only need the largest id for a particular message_id

SELECT max(id), message_id FROM table
 where to_user = ? 
 and deleted != ? 
 and del2 != ?
 and is_read = '0'
group by message_id 
  order by id desc

Comments

-1

Try DISTINCT keyword. This will work definitely:

SELECT DISTINCT(message_id), id FROM table;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.