2 different small query vs 1 query with subquery

前端 未结 4 1243
无人及你
无人及你 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: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";
      }
    }
    

提交回复
热议问题