PHP循环记录非常慢

I'm using PDO. So I have a statement that prepares a query to select a bunch of records. Example:

   //select duplicates
   $stmt = $this->db->prepare('SELECT Name COUNT( * ) AS CNT
            FROM  `Test`
            GROUP BY Name
            HAVING CNT > 1');

   $stmt2 = $this->db->prepare('SELECT * FROM Test2 WHERE TName = ?');

Note that I do need all data selected, not certain columns. The table contains 5k records, sometimes more. I need to select all 5k records and for each of them I need to execute another query to select something else.

   $arr = array();
   while ($row = $stmt->fetch(DB::FETCH_ASSOC)) {
       $stmt2->execute($row['Name']);
       $arr[] = $stmt2->fetchAll(DB::FETCH_ASSOC);
   }

I know I can use joins but for my case joins will not work, because I need to loop through the data and execute stmt2 for each stmt1 row.

When I run this it takes up to 10-15 minutes which I can't allow, I need it to be faster. Can anyone tell me what the problem is? 5k records does not seem that much to loop through.

      STMT1 returns up to 5.5k records

I need data for each duplicate returned:

Joins won't work? HIGHLY HIGHLY doubtful:

SELECT test2.*, count(test.name) AS cnt
FROM test
LEFT JOIN test2 ON test2.id = test.id
GROUP BY test.name
HAVING (cnt > 1)

another try, given the OP's troubles:

SELECT *
FROM test2
WHERE name IN (
   SELECT DISTINCT name
   FROM test
   GROUP BY name
   HAVING (count(*) > 1)
)

If for some reason you can't use JOINS, create a stored procudure, which will take an id as argument and return the data you need.

You can also use dictionary encoding for your Name, because operations with integers are much more faster.