douren7179 2016-05-11 11:50
浏览 83

PHP和Mysql - 嵌套循环

I have 2 tables - products and productimages. product has unique id and title. productimages has productid and imageurl. these are examples of my tables:

products:

|id|title    |
_____________
|1 |Laptop   |
|2 |Speakers |

productimages:

|productid|imageurl|
___________________
|    1    |lap1.png|
|    1    |lap2.png|
|    1    |lap3.png|
|    2    |spe1.png|

Right now I have a nested loop in PHP. loop through all rows of -> select * from products and for every product inside the loop -> select * from productimages where productid = id which is basically another loop inside the first loop.

and then I take all productimages into array and decode to JSON [title,photos].

Now imagine you have 2 million rows in productimages, the query times are too high, is there any way to make it more efficient?

$query = "SELECT * FROM products ORDER BY id LIMIT 10;
$result = mysqli_query($con,$query);

if(mysqli_num_rows($result)>0)
{
    $response = array();
    while($row = mysqli_fetch_assoc($result)) {
        $photos = array();
        $id = $row["id"];
        $title = $row["title"];         

        $queryp = "select imageurl from productimages where productid= '".$id."';";
        $resultp = mysqli_query($con,$queryp);

        if(mysqli_num_rows($resultp)>0)
        {
            while($row2 = mysqli_fetch_assoc($resultp)) {
                $photourl = $row2["imageurl"];
                array_push($photos,$photourl);
            }
        }
     }
  }
  • 写回答

3条回答 默认 最新

  • dqp21271 2016-05-11 12:01
    关注

    Some betterment for you could be:

    1) Don't use select *. Use column names instead. e.g. select products.id, products.title, productimages.imageurl

    2) Use JOIN instead of nested loop

    So, you can try querying data like:

    select products.id, products.title, productimages.imageurl
    from products
    join productimages on products.id = productimages.productid
    ORDER BY products.id LIMIT 10
    
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号