sql distinct 多列问题

 查询单列,使用select distinct name from photos;是没有问题的。

但若想查询多列,如select distinct name,nickname,department from photos;是将三列完全相同的内容过滤掉,但凡三列有一列不同,均会列出来。
若将distinct放后面,如select nickname,department,distinct name from photos;报错,distinct必须放在开头。将distinct放到where里,也是报错。
可以使用select *, count(distinct name) from photos group by name;最后一项是多余的,不用管就行了,目的可以达到其中,group by 必须放在 order by 和 limit之前,不然会报错。

或者可以使用select * from photos where id in (select max(id) from photos group by name),但是执行效率很低,能明显感觉出数据库的处理时间。 如果数据可以保证--随着id递增,数据越新,则使用此语句可查询出最新结果。上面的语句则不保证。

猜你喜欢

转载自hae.iteye.com/blog/2183736