views:

123

answers:

1

Hy is theere a query where i can do both querys in one?

This is the first

$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)";

And this is the second

  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);
        }

My question is can i doit the above without a php code just pure sql?

+2  A: 

In MySQL, you can use a join right after UPDATE. In your example, this might look something like:

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}
Andomar
Wow you must be a sql gur thanks this worked for me :-)
streetparade
Andomar - Can this be done for a single table only?Eg: select * from table;//Process somethingupdate table set blah=1
Bart J
@Bart J: Yes, an UPDATE can only update one table at a time. If you want to ensure an update that spans multiple table succeeds or fails as a whole: that's what transactions are made for.
Andomar