Home > php教程 > PHP开发 > body text

Usage of distinct in SQL (analysis of four examples)

高洛峰
Release: 2016-12-13 09:31:29
Original
2195 people have browsed it

When using mysql, sometimes you need to query for unique records in a certain field. Although mysql provides the distinct keyword to filter out redundant duplicate records and keep only one, it is often only used to return the number of unique records. , instead of using it to return all values ​​without duplicate records. The reason is that distinct can only return its target field and cannot return other fields. This problem has troubled me for a long time. If it cannot be solved with distinct, I can only solve it with a double loop query, which is very difficult for a large amount of data. For the website, it will undoubtedly directly affect the efficiency, so I wasted a lot of time.

In the table, there may be duplicate values. This is not a problem, but sometimes you may want to just list distinct values. The keyword distinct is used to return uniquely distinct values.

Table A:

Usage of distinct in SQL (analysis of four examples)

Example 1

select distinct name from A
Copy after login

The results after execution are as follows:

Usage of distinct in SQL (analysis of four examples)

Example 2

select distinct name, id from A
Copy after login

The results after execution are as follows:

Usage of distinct in SQL (analysis of four examples)

In fact, it is based on "name+id" To remove duplicates, distinct acts on both name and id. This method is supported by Access and SQL Server at the same time.

Example 3: Statistics

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

Example 4

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

Others

The fields displayed in the select statement can only be the fields specified by distinct, and other fields are not possible. For example, if table A has a "Remarks" column, if you want to obtain the distinct name and the corresponding "Remarks" field, it is impossible to do so directly through distinct.


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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!