search
HomeDatabaseMysql TutorialMySQL中Distinct和Group By语句的基本使用教程_MySQL

MySQL Distinct 去掉查询结果重复记录
DISTINCT
使用 DISTINCT 关键字可以去掉查询中某个字段的重复记录。
语法:

SELECT DISTINCT(column) FROM tb_name


例子:
假定 user 表有如下记录:

uid username
1 小李
2 小张
3 小李
4 小王
5 小李
6 小张

SQL 语句:
SELECT DISTINCT(username) FROM user
返回查询结果如下:

username
小李
小张
小王

提示
使用 DISTINCT 关键字去掉重复记录具有较大的局限性。DISTINCT() 只能包含一个字段且查询结果也只返回该字段而非数据完整记录(如上例所示)。
可以尝试使用如下语法:

SELECT DISTINCT(column),column1,column2,... FROM tb_name

该查询结果将返回列出的所有字段,但该查询往往使 column 的唯一性失效,且 column 1,column 2,… 不能放在 DISTINCT(column) 之前。
上面的例子如果要返回如下结果(这往往是期望中的):

uid username
1 小李
2 小张
3 小王

这时候就要用到 GROUP BY 关键字。

MySQL Group By 数据分组
GROUP BY
MySQL中 使用 GROUP BY 关键字用于对某个或某些字段查询分组,并返回重复记录的第一条。
语法:

SELECT column,... FROM tb_name GROUP BY column1,column2 ...

user 表记录如下:

uid username
1 小李
2 小张
3 小李
4 小王
5 小李
6 小张

对上面的 user 表做查询如下:

SELECT * FROM user GROUP BY username

返回查询结果如下:

uid username
1 小李
2 小张
3 小王

说明
GROUP BY 语法在 MySQL 数据库中的用法与其他数据库相差较大。对于标准 SQL 而言,GROUP BY 一定要结合聚合函数使用,而且选择的字段除了聚合函数外,还必须在 GROUP BY 中出现。但是在 MySQL 中扩展了 GROUP BY 的功能:
不加聚合函数的情况下,返回的结果是 GROUP BY 结果集中第一行,如上面例子所示。
GROUP BY 结合聚合函数的时候,选择的字段不必在 GROUP BY 中存在,MySQL 具有隐含字段的功能。
所以我们可以根据 MySQL 对 GROUP BY 的扩展特性,结合另外一些关键字如 ORDER BY 等,方便的得到想要的查询结果。
例子 2:

SELECT * FROM user GROUP BY username,uid

返回查询结果如下:

uid username
1 小李
3 小李
5 小李
2 小张
6 小张
4 小王

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does MySQL handle concurrency compared to other RDBMS?How does MySQL handle concurrency compared to other RDBMS?Apr 29, 2025 am 12:44 AM

MySQLhandlesconcurrencyusingamixofrow-levelandtable-levellocking,primarilythroughInnoDB'srow-levellocking.ComparedtootherRDBMS,MySQL'sapproachisefficientformanyusecasesbutmayfacechallengeswithdeadlocksandlacksadvancedfeatureslikePostgreSQL'sSerializa

How does MySQL handle transactions compared to other relational databases?How does MySQL handle transactions compared to other relational databases?Apr 29, 2025 am 12:37 AM

MySQLhandlestransactionseffectivelyusingtheInnoDBengine,supportingACIDpropertiessimilartoPostgreSQLandOracle.1)MySQLusesREPEATABLEREADasthedefaultisolationlevel,whichcanbeadjustedtoREADCOMMITTEDforhigh-trafficscenarios.2)Itoptimizesperformancewithabu

What are the data types available in MySQL?What are the data types available in MySQL?Apr 29, 2025 am 12:28 AM

MySQL data types are divided into numerical, date and time, string, binary and spatial types. Selecting the correct type can optimize database performance and data storage.

What are some best practices for writing efficient SQL queries in MySQL?What are some best practices for writing efficient SQL queries in MySQL?Apr 29, 2025 am 12:24 AM

Best practices include: 1) Understanding the data structure and MySQL processing methods, 2) Appropriate indexing, 3) Avoid SELECT*, 4) Using appropriate JOIN types, 5) Use subqueries with caution, 6) Analyzing queries with EXPLAIN, 7) Consider the impact of queries on server resources, 8) Maintain the database regularly. These practices can make MySQL queries not only fast, but also maintainability, scalability and resource efficiency.

How does MySQL differ from PostgreSQL?How does MySQL differ from PostgreSQL?Apr 29, 2025 am 12:23 AM

MySQLisbetterforspeedandsimplicity,suitableforwebapplications;PostgreSQLexcelsincomplexdatascenarioswithrobustfeatures.MySQLisidealforquickprojectsandread-heavytasks,whilePostgreSQLispreferredforapplicationsrequiringstrictdataintegrityandadvancedSQLf

How does MySQL handle data replication?How does MySQL handle data replication?Apr 28, 2025 am 12:25 AM

MySQL processes data replication through three modes: asynchronous, semi-synchronous and group replication. 1) Asynchronous replication performance is high but data may be lost. 2) Semi-synchronous replication improves data security but increases latency. 3) Group replication supports multi-master replication and failover, suitable for high availability requirements.

How can you use the EXPLAIN statement to analyze query performance?How can you use the EXPLAIN statement to analyze query performance?Apr 28, 2025 am 12:24 AM

The EXPLAIN statement can be used to analyze and improve SQL query performance. 1. Execute the EXPLAIN statement to view the query plan. 2. Analyze the output results, pay attention to access type, index usage and JOIN order. 3. Create or adjust indexes based on the analysis results, optimize JOIN operations, and avoid full table scanning to improve query efficiency.

How do you back up and restore a MySQL database?How do you back up and restore a MySQL database?Apr 28, 2025 am 12:23 AM

Using mysqldump for logical backup and MySQLEnterpriseBackup for hot backup are effective ways to back up MySQL databases. 1. Use mysqldump to back up the database: mysqldump-uroot-pmydatabase>mydatabase_backup.sql. 2. Use MySQLEnterpriseBackup for hot backup: mysqlbackup--user=root-password=password--backup-dir=/path/to/backupbackup. When recovering, use the corresponding life

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools