SELECTDISTINCT column1,column2 FROM table_name WHERE where_conditions; mysql> selectdistinct sex,age from student; +--------+------+ | sex | age | +--------+------+ | male | 10 | | female | 12 | | male | 11 | | male | NULL | | female | 11 | +--------+------+ 5 rows in set (0.02 sec)
group by 的使用
對于基礎(chǔ)去重來說,group by的使用和distinct類似。
單列去重
語法:
SELECTcolumnsFROM table_name WHERE where_conditions GROUPBYcolumns;
執(zhí)行:
mysql> select age from student groupby age; +------+ | age | +------+ | 10 | | 12 | | 11 | | NULL | +------+ 4 rows in set (0.02 sec)
多列去重
語法:
SELECTcolumnsFROM table_name WHERE where_conditions GROUPBYcolumns;
執(zhí)行:
mysql> select sex,age from student groupby sex,age; +--------+------+ | sex | age | +--------+------+ | male | 10 | | female | 12 | | male | 11 | | male | NULL | | female | 11 | +--------+------+ 5 rows in set (0.03 sec)
GROUP BY implicitly sorts by default (that is, in the absence of ASC or DESC designators for GROUP BY columns). However, relying on implicit GROUP BY sorting (that is, sorting in the absence of ASC or DESC designators) or explicit sorting for GROUP BY (that is, by using explicit ASC or DESC designators for GROUP BY columns) is deprecated. To produce a given sort order, provide an ORDER BY clause.
大致解釋一下:
GROUP BY 默認隱式排序(指在 GROUP BY 列沒有 ASC 或 DESC 指示符的情況下也會進行排序)。然而,GROUP BY 進行顯式或隱式排序已經(jīng)過時(deprecated)了,要生成給定的排序順序,請?zhí)峁?ORDER BY 子句。
Previously (MySQL 5.7 and lower), GROUP BY sorted implicitly under certain conditions. In MySQL 8.0, that no longer occurs, so specifying ORDER BY NULL at the end to suppress implicit sorting (as was done previously) is no longer necessary. However, query results may differ from previous MySQL versions. To produce a given sort order, provide an ORDER BY clause.
大致解釋一下:
從前(MySQL5.7 版本之前),Group by 會根據(jù)確定的條件進行隱式排序。在 MySQL 8.0 中,已經(jīng)移除了這個功能,所以不再需要通過添加order by null來禁止隱式排序了,但是,查詢結(jié)果可能與以前的 MySQL 版本不同。要生成給定順序的結(jié)果,請按通過ORDER BY指定需要進行排序的字段。