2 different small query vs 1 query with subquery

前端 未结 4 1240
无人及你
无人及你 2021-01-04 05:04

I have table like this

name       | personal_number 
-----------------------------------------
Jon        | 222
Alex       | 555
Jon        | 222
Jimmy               


        
相关标签:
4条回答
  • 2021-01-04 05:12

    Since indexing is not done so the 1 is slow,as it has to match personal_numbers from selected personal_numbers. If indexing is done it consumes less time than earlier. Variant 2 is a direct query hence its faster.

    0 讨论(0)
  • 2021-01-04 05:27

    It seems that subqueries are very slow as mentioned in this article http://www.mysqlperformanceblog.com/2010/10/25/mysql-limitations-part-3-subqueries.

    You should try to avoid having subqueries and use joining instead.

    0 讨论(0)
  • 2021-01-04 05:30

    First query has heavy subquery. You must avoid this. The best solution for your problem is only one query:

    SELECT name FROM mytable GROUP BY personal_number HAVING COUNT(*) > 1;
    

    This query will return you each repeated name only once. If you want to display the name of the duplicate as many times as they met you must use next query:

    SELECT name, COUNT(*) AS count FROM mytable GROUP BY personal_number HAVING COUNT(*) > 1;
    

    And then in PHP do something like this:

    foreach ($rows as $row) {
      for ($i = 0; $i++; $i < $row['count']) {
        echo $row['name'] . "\n";
      }
    }
    
    0 讨论(0)
  • 2021-01-04 05:32

    This should be quicker:

    SELECT  name  FROM mytable join (
            SELECT  personal_number  FROM mytable  GROUP BY personal_number
            HAVING COUNT(*) > 1
    )a using (personel_number)
    

    Edit: If this is faster than variant 1, then it means at variant 1 mysql reproduces the inner table for each record again and again.

    0 讨论(0)
提交回复
热议问题