dsd119120 2012-11-08 15:16
浏览 112
已采纳

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 15: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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度