SQL中的distinct关键字的正确用法

distinct 并不是一个函数,它只是一个修饰词,它的意思是过滤所有的重复返回行

因此以下语句:

select distinct(user.cellphone), user.points from user;

可能会返回重复的手机号的行,因为distinct 并不是跟(user.cellphone)结合的,它实际上是跟select结合的,将其修正为正确的写法:

select distinct user.cellphone, user.points from user;

这条语句的含义是返回user.cellphoneuser.points结合的唯一行,因此依然会有重复的手机号返回,以下语句则不会有重复的手机号返回,因为返回行总共只有一列:

select distinct user.cellphone from user;

如果想在返回唯一的手机号时,顺便携带points,则应当使用group by:

select user.cellphone, user.points from user group by user.cellphone;

One thought on “SQL中的distinct关键字的正确用法”

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注