以下是内存限制问题:
使用PHP从MySQL中抓取190k行,空白页?内存还是缓冲区?
我今天达到内存限制的一个重要原因是因为这个脚本:
当我获取参考号(在我的申请中有成本)时,我想获取价格(它的成本)。
参考号价格可以在deal.price中找到,但如果参考号/订单是产品,我需要在deals_products.price中查找价格。
这是我的问题,我从开始
SELECT `refnumbers`.`refno`, `deals`.`price`, `refnumbers`.`order_id` FROM `refnumbers` JOIN `deals` ON (`deals`.`ID` = `refnumbers`.`deal_id`)
然后,为了得到价格,我总是需要这段代码(我想得到你的帮助,删除它,这样它就可以在查询中找到)
foreach($refnumbers as $ref)
{
$isProduct = DB::select('product_id')->from('orders_chosenoptions')
->where('order_id', '=', $ref['order_id'])->execute()->get('product_id', 0);
if($isProduct > 0)
{
$price = DB::select('price')->from('deals_products')
->where('id', '=', $isProduct)
->execute()->get('price');
}else{
$price = $ref['price'];
}
}
(我使用的是Kohana Query Builder,但查询应该是可读的,以了解发生了什么)
所以你可以看到这是非常无效的,1)我运行一个查询,2)我遍历每一行并运行两个查询,以确保我得到正确的价格。
当我浏览190k行时,它基本上会运行2x1900k的单个查询作为额外的
我怎么可能跳过这个,从第一个查询就得到正确的价格?
任何答案都将不胜感激。
注意:我不能修改数据库的设计结构。
更新:
我已经成功地尝试了这个查询:
SELECT `refnumbers`.`refno`,
CASE WHEN orders_chosenoptions.order_id IS NOT NULL
THEN (SELECT price FROM deals_products WHERE id = orders_chosenoptions.product_id)
ELSE deals.price
END AS price,
`refnumbers`.`order_id`
FROM `refnumbers`
JOIN `deals` ON (`deals`.`ID` = `refnumbers`.`deal_id`)
LEFT JOIN orders_chosenoptions ON (orders_chosenoptions.order_id = refnumbers.order_id)
看起来很有效,但会漏掉一些行吗?我做错了吗?
据我所知(没有表定义),您正在处理4个表。为了在一个查询中实现您想要的内容,您必须连接所有表,并使用MySQL的IF()
测试orders_chosenoptions.product_id
,以有条件地选择deals_products.price
或deals.price
。
SELECT r.refno, IF(cp.product_id > 0, dp.price, d.price) AS price, r.order_id
FROM refnumbers r
JOIN deals d ON d.ID = r.deal_id
LEFT JOIN orders_chosenoptions oc ON r.order_id = oc.order_id
LEFT JOIN deals_product dp ON oc.product_id = dp.id
WHERE r.deal_id = ...