2011-08-24 78 views
0

我有一個查詢,看起來像這樣:MYSQL乘以if?

//execute the SQL query and return records 
$result = mysql_query("SELECT SUM(ps_order_detail.product_weight) as total_provision, COUNT(ps_order_detail.id_order_detail) as antal_ordrar, ps_customer.firstname 
        FROM ps_order_detail 
        JOIN ps_orders ON ps_order_detail.id_order = ps_orders.id_order 
        JOIN ps_order_history ON ps_orders.id_order = ps_order_history.id_order 
        JOIN ps_customer ON ps_orders.id_customer = ps_customer.id_customer 
        WHERE MONTH(ps_order_history.date_add) = MONTH(CURDATE()) AND (ps_order_history.id_order_state) = '4' OR (ps_order_history.id_order_state) = '13' 
        GROUP BY ps_orders.id_customer 
        ORDER BY SUM(ps_order_detail.product_weight) DESC 
        "); 


//fetch tha data from the database 
while ($row = mysql_fetch_array($result)) 
{ 
    echo '<font size="3">'; 
    echo " Namn: ".$row{'firstname'}. ""; 
    echo " Provision: ".$row{'total_provision'}. ""; 
    echo " Abonnemang: ".$row{'antal_ordrar'}. ""; 
    echo '<br>'; 
    echo '</font size>'; 
} 

它工作正常,但我瓦納做的是,如果結果「antal_ordrar」大於說50餘次瓦納繁衍的結果「total_provision」 1,2 (添加額外的20%的結果)

即時通訊新的和有點卡住了。有任何想法嗎?

回答

0
SELECT SUM(ps_order_detail.product_weight) * 
    IF(COUNT(ps_order_detail.id_order_detail) > 50, 1.2, 1) AS total_provision, 
    COUNT(ps_order_detail.id_order_detail) AS antal_ordrar, ... 
0

首先,在一個子查詢包裹的:

SELECT 
    -- use the if statement 
    IF(antal_ordrar > 50, total_provision * 1.2, total_provision), 
    antal_ordrar, 
    firstname 
FROM 
    -- create a subquery so you can reuse the data. 
    (SELECT SUM(ps_order_detail.product_weight) as total_provision, 
      COUNT(ps_order_detail.id_order_detail) as antal_ordrar, 
      ps_customer.firstname as firstname 
     FROM ps_order_detail 
     -- are you sure you need this many joins?  
     JOIN ps_orders ON ps_order_detail.id_order = ps_orders.id_order 
     JOIN ps_order_history ON ps_orders.id_order = ps_order_history.id_order 
     JOIN ps_customer ON ps_orders.id_customer = ps_customer.id_customer 
     -- group by normally uses the 'having' keyword. 
     WHERE MONTH(ps_order_history.date_add) = MONTH(CURDATE()) 
      AND (ps_order_history.id_order_state) = '4' 
      OR (ps_order_history.id_order_state) = '13' 
     GROUP BY ps_orders.id_customer 
     ORDER BY SUM(ps_order_detail.product_weight) DESC) 
    -- an alias for your subquery so you can treat it like a table. 
    tbl; 

就注意到了這一點。括號表示括號時:$row{'total_provision'}應該是$row['total_provision']

-1

嘗試添加選擇

if (antal_ordrar > 50, total_provision * 1.2, total_provision) as total_provision 
+0

TNX ALOT的敏捷和快速方向的所有!使用SELECT SUM(ps_order_detail.product_weight)* IF(COUNT(ps_order_detail.id_order_detail)> 50,1.2,1) 作爲total_provision – HangerS