我想从表中选择唯一的一行,有人可以帮帮我吗?
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 |
+----+-----+------+
我需要像
这样的东西+----+-----+------+
| id | message_id |
+----+-----+------+
| 3 | 23 |
| 4 | 24 |
| 5 | 25 |
+----+-----+------+
答案 0 :(得分:4)
试试这个:
SELECT MAX(id), message_id
FROM tablename
GROUP BY message_id
如果您还有其他字段:
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
答案 1 :(得分:1)
如果您只需要特定message_id的最大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
答案 2 :(得分:-1)
尝试使用DISTINCT关键字。这肯定会有效:
SELECT DISTINCT(message_id), id FROM table;