Mysql distinct usage-how to filter non-duplicate data in mysql

Source: Internet
Author: User
Tags mysql manual


Mysql distinct usage-when using mysql to filter out non-duplicate data, you sometimes need to query records with no repeated fields, although mysql provides the keyword distinct to filter out redundant duplicate records and retain only one record, it is often used to return the number of records that do not repeat, rather than returning all values that do not record duplication. The reason is that distinct can only return its target field, but cannot return other fields. Let's take a look at the example below: table id name 1 a 2 B 3 c 4 c 5 B for example, if I want to use a statement to query all the data with no duplicate names, we must use distinct to remove redundant duplicate records. Www.2cto.com select distinct name from table the result is: name a B c seems to have achieved the effect, but what do I want to get is the id value? Change 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 for a long time, finally, I found a usage in the mysql manual. www.2cto.com used group_concat (distinct name) and group by name to implement the functions that I needed 5.0 to support. suddenly, the ghost machine flashed. Since the group_concat function can be used, can other functions be used? Use the count function for a try. Now the complete statement is released: select *, count (distinct name) from table group by name result: id name count (distinct name) 1 a 1 2 B 1 3 c 1 by the way, group by must be placed before order by and limit, otherwise an error will be reported... OK, author Xie chunye

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.