2009-11-03 68 views
2

是否有查詢可以在兩個查詢中進行查詢?在一個查詢中進行選擇並更新

這是第

$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代碼只是純粹的SQL?

+0

你使用什麼數據庫服務器? MySQL,SQL Server,Oracle? – Andomar 2009-11-03 10:37:33

+0

Mysql是數據庫服務器 – streetparade 2009-11-03 10:38:54

回答

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} 
+0

哇你必須是一個sql gur謝謝這對我工作:-) – streetparade 2009-11-03 11:12:53

+0

Andomar - 這隻能做一個單一的表? 例如:select * from table; //處理一些東西 update table set blah = 1 – 2009-11-03 18:07:34

+0

@ JJ:是的,UPDATE一次只能更新一個表。如果您希望確保跨越多個表成功或整體失敗的更新:那就是進行交易的原因。 – Andomar 2009-11-03 22:54:31

相關問題