在一个查询中进行选择和更新

时间:2009-11-03 10:27:44

标签: php sql select sql-update

是否有查询,我可以在一个查询中进行查询?

这是第一个

$q = "select c.id as campaignId,c.priceFactor,
              o.cid,o.bloggerPrice,o.state as state,o.customerPrice,o.id as orderId,o.listPrice,o.basicPrice
              from campaign c, orders o
              where c.id={$campaignId}
              and c.id = o.cid
              and o.state in (8,9)";

这是第二次

  foreach($orders as $order)
        {
             $listPrice      = $order->priceFactor * $order->basicPrice;

             if($order->bloggerPrice < $listPrice || $order->customerPrice < $listPrice)
             {
                $order->bloggerPrice  = $listPrice;
                $order->customerPrice = $listPrice;
             }

             $qUpdate       = "update orders set
                               listPrice = {$listPrice},bloggerPrice={$order->bloggerPrice},
                               customerPrice ={$order->customerPrice}
                               where id=$order->orderId and cid={$order->cid}";

            // $this->db->q($qUpdate);
        }

我的问题是:我可以在没有PHP代码的情况下执行上述操作吗?

1 个答案:

答案 0 :(得分:4)

在MySQL中,您可以在UPDATE之后立即使用连接。在您的示例中,这可能类似于:

update Orders o
inner join Campaign c on c.id = o.cid
set
    listPrice = o.priceFactor * order.basicPrice
,   bloggerPrice = case 
        when o.bloggerPrice < o.priceFactor * order.basicPrice
            then o.priceFactor * order.basicPrice
            else bloggerPrice
        end
,   listPrice = case 
        when o.customerPrice < o.priceFactor * order.basicPrice
            then o.priceFactor * order.basicPrice
            else listPrice
        end
where o.state in (8,9)
and c.id = {$campaignId}