我有两个表-产品和产品映像。产品具有唯一的id和标题。productivimages有productid和imageurl。以下是我的表格示例:
产品:
|id|title |
_____________
|1 |Laptop |
|2 |Speakers |
生产图像:
|productid|imageurl|
___________________
| 1 |lap1.png|
| 1 |lap2.png|
| 1 |lap3.png|
| 2 |spe1.png|
现在我在PHP中有一个嵌套循环。循环遍历->select * from products
的所有行并且对于循环内的每个乘积->CCD_ 2,其基本上是第一循环内的另一个循环。
然后我将所有的产品图像放入数组中,并解码为JSON[标题,照片]。
现在想象一下,你在产品图中有200万行,查询次数太高了,有什么方法可以提高效率吗?
$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);
}
}
}
}
对您的一些改进可能是:
1) 不要使用select *
。请改用列名。例如select products.id, products.title, productimages.imageurl
2) 使用JOIN
而不是嵌套循环
因此,您可以尝试查询以下数据:
select products.id, products.title, productimages.imageurl
from products
join productimages on products.id = productimages.productid
ORDER BY products.id LIMIT 10
这种情况并不少见——在一对多关系中有两个表。
如果可以避免SQL调用,但需要对一两个SQL调用做出决定,那么永远不应该在循环中嵌套SQL调用。
单个SQL调用可以是:
SELECT id, title, imageURL
FROM products LEFT JOIN productImages ON id=productid
这样做的缺点是,你要为每个产品提取几次标题,这是浪费。
使用两个SQL语句,您可以为每个产品下载一次标题:
SELECT id, title FROM products
这个查询的结果可以存储在一个关联数组中,这样您就可以查找每个id的标题。
第二个查询是:
SELECT productid, imageURL FROM productImages ORDER BY productid, imageURL
您可以循环浏览此查询的结果,边查询边吐出标题。
要将图像与产品一起保存,您可以在产品表中添加一列imageurl
。使用,
收集图像名称,并将该图像名称字符串插入products表格。你的桌子看起来像下面。
+--------------+--------------+---------------------------+
| id | title | imageurl |
+--------------+--------------+---------------------------+
| 1 | Laptop | lap1.png,lap2.png,lap3.png|
+--------------+--------------+---------------------------+
| 2 | Speakers | spe1.png |
希望你理解我的解释。