dsd119120 2012-11-08 07:16
浏览 113
已采纳

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:

  • 写回答

2条回答 默认 最新

  • doukong1901 2012-11-08 07:23
    关注

    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)
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部