Home >Database >Mysql Tutorial >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:
## Use distinct to return unique user names: select distinct name from user;, the result is: 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: 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!