How to query duplicate fields in a MySQL large table

Source: Internet
Author: User

How can I query repeated fields in a MySQL large table? This is a problem that many people have encountered. The following describes how to query duplicate fields in a MySQL large table for your reference.

There is a large table in the database. You need to find a duplicate record id in the name for comparison.

It is easy to find fields with unique names in the database.

 
 
  1. SELECT min(`id`),`name`   
  2. FROM `table`   
  3. GROUP BY `name`;  

However, the id value of the repeated field cannot be obtained. Only the smallest id value is returned)

It is easy to query which fields are repeated.

 
 
  1. SELECT `name`,count(`name`) as count   
  2. FROM `table`   
  3. GROUP BY `name` HAVING count(`name`) >1   
  4. ORDER BY count DESC;  

However, to query the id of a repeated field at a time, you must use the subquery. Therefore, use the following statement to query duplicate fields in a MySQL large table.

 
 
  1. SELECT `id`,`name`   
  2. FROM `table`   
  3. WHERE `name` in (   
  4.    SELECT `name`   
  5.    FROM `table`   
  6.    GROUP BY `name` HAVING count(`name`) >1  
  7. );  

However, this statement is too inefficient in mysql, and mysql does not generate a zero-value table for the subquery.

Therefore, create a zero-time table first.

 
 
  1. create table `tmptable` as (  
  2.    SELECT `name`   
  3.    FROM `table`   
  4.    GROUP BY `name` HAVING count(`name`) >1  
  5. );  

Then use multi-Table connection to query

 
 
  1. SELECT a.`id`, a.`name`   
  2. FROM `table` a, `tmptable` t   
  3. WHERE a.`name` = t.`name`;  

The result is coming soon.

Duplicate with distinct

 
 
  1. SELECT distinct a.`id`, a.`name`   
  2. FROM `table` a, `tmptable` t   
  3. WHERE a.`name` = t.`name`;  

Mysql query case

How to query duplicate records in MYSQL

Implementation of MySQL random Query

Example of the number of MySQL query results

Optimization of MySQL query Paging

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.