简体   繁体   中英

mysql select only unique row

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

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

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

Try DISTINCT keyword. This will work definitely:

SELECT DISTINCT(message_id), id FROM table;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM