SQL: How to keep rows order with DISTINCT?

China☆狼群 提交于 2019-11-29 07:34:27

the distinct key word is doing what it's supposed to do, return one row each with a given column value. Distinct doesn't allow you to specify which such row will be returned, and it's clear from the original query that such an ordering is allowed (there is a row with id 443 that follows a row with id 429).

To take control of what rows will be returned, you need to reformulate the query. A typical solution I'll take is to use a group by, selecting the group column and the desired row from each group, something to the effect of

SELECT message.id, MAX(message.created_at) FROM message GROUP BY message.id;

If I need to do more, I'll use this sort of query as a subselect in a larger query, possibly joining on the id field to get more fields from the preferred row, Or ordering the query in a particular way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!