Home > Database > Mysql Tutorial > body text

What is the usage of mysql distinct

hzc
Release: 2020-06-13 16:16:09
Original
4921 people have browsed it

What is the usage of mysql distinct

Usage of distinct in mysql

When using mysql, sometimes you need to query for non-duplicate records in a certain field. In this case, you can Use the distinct keyword provided by mysql to filter duplicate records, but in practice we often use distinct to return the number of unique fields (count(distinct id)). The reason is that distinct can only return its target field, and Other fields cannot be returned. For example, the following table user:

What is the usage of mysql distinct

## Use distinct to return unique user names: select distinct name from user;, the result is:

What is the usage of mysql distinct

In this way, only unique user names are queried, but the user's id is not queried: select distinct name,id from user;, the result is:

What is the usage of mysql distinct

distinct name,id MySQL will think that it is necessary to filter out records with duplicate fields of name and id. If SQL is written like this: select id,distinct name from user, like this MySQL will report an error because distinct must be placed at the beginning of the field to be queried.

So distinct is generally used to query the number of unique records.

If you want to query unique records, you can sometimes use group by:

select id,name from user group by name;

Recommended tutorial: "

mysql tutorial

The above is the detailed content of What is the usage of mysql distinct. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template