SQL distinct statement

Source: Internet
Author: User

The distinct keyword of the SQL distinct statement is used to filter out redundant duplicate records and retain only one record, but it is often used to return the number of records that are not repeated, instead of using it to return all non-record values. The reason is that distinct is only used for dual-loop queries, which will undoubtedly directly affect the efficiency of a station with a large data volume. -Let's take a look at the example below: The table Field 1 Field 2 id name 1 a 2 B 3 c 4 c 5 B library structure is like this, this is just a simple example, the actual situation is much more complicated. For example, if you want to use a statement to query all data with no duplicate names, you must use distinct to remove redundant duplicate records.

select distinct name from table 

 

The result is: ---------- name a c seems to have achieved results, but what do I want to get is the id value? Modify the query statement:
select distinct name, id from table 

 

The result will be: ---------- id name 1 a 2 B 3 c 4 c 5 B distinct. Why didn't it work? The function is effective, but it also applies to two fields, that is, it must have the same id and name to be excluded and then modify the query statement:
select id, distinct name from table 

 

Unfortunately, you cannot get anything except the error message. You must start with distinct. Is it difficult to place distinct in the where condition? Yes. An error is returned. -------------------------------------------------------- The following method is feasible:
select *, count(distinct name) from table group by name 

 

Result:
   id name count(distinct name)    1 a 1    2 b 1    3 c 1 

 

The last item is redundant, so you don't have to worry about it. To achieve group by, you must put it before order by and limit. Otherwise, an error will be reported.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.