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

str*_*ade 2 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)";
Run Code Online (Sandbox Code Playgroud)

这是第二个

  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);
        }
Run Code Online (Sandbox Code Playgroud)

我的问题是:如果没有纯PHP的PHP代码,是否可以完成上述操作?

And*_*mar 5

在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}
Run Code Online (Sandbox Code Playgroud)