Mysql中DISTINCT的注意点

重新开一遍《mysql必知必会》,就一些知识点加以记录

DISTINCT关键字

SQL SELECT DISTINCT 语句

在表中,可能会包含重复值。这并不成问题,不过,有时您也许希望仅仅列出不同(distinct)的值。

关键词 DISTINCT 用于返回唯一不同的值。

下面说说DISTINCT关键字使用时候的几种情况

  • select distinct name from A
    执行结果:A中所有不重复的name

  • select distinct name, id from A
    实际上是根据“name+id”来去重,distinct同时作用在了name和id上

  • select count(distinct name) from A; --表中name去重后的数目;select count(distinct name, id) from A; --SQL Server和Access都不支持

  • select id, distinct name from A; --会提示错误,因为distinct必须放在开头

注意:
distinct语句中select显示的字段只能是distinct指定的字段,其他字段是不可能出现的。例如,假如表A有“备注”列,如果想获取distinc name,以及对应的“备注”字段,想直接通过distinct是不可能实现的。

参考:https://blog.csdn.net/jingshaozhi/article/details/78061341

你可能感兴趣的:(MySQL)