2016-08-24 36 views
0

我有一個產品price 2列表示正常價格和new_price代表產品的報價。當我按價格訂購時,如果兩列都填滿了,我無法得到正確的訂單。現在它先以新價格然後按價格訂購。我想以某種方式連接價格。Mysql通過2列表示價格和新價格

if($order==1) 
{ 
    $order_by='Produse.New_price ASC,Produse.Price ASC'; 
} 

if($order==2) 
{ 
    $order_by='Produse.New_Price DESC,Produse.Price DESC'; 
}  

if($order==3) 
{ 
    $order_by='Produse.Nume_Prod ASC'; 
} 

if($order==4) 
{ 
    $order_by='Produse.Nume_Prod DESC'; 
} 

if($order==0) 
{ 
    $order_by='Produse.Nume_Prod DESC'; 
} 
     $stmt=$dbh->prepare("Select * FROM Produse 
           INNER JOIN Categorii on Produse.ID_Categorie=Categorii.ID_Categorie 
          where Categorii.Nume_Categ=:id 
          ORDER BY $order_by"); 
     $stmt->bindParam(':id',$id,PDO::PARAM_INT); 
     $stmt->execute(); 
+0

使用COALESCE返回在新的價格的第一個非空價格vs price ...'通過合併訂購('Produse.new_price,produse.price)'這個假設當兩者都存在時,您想以新價格訂購。並且新價格爲空,您只需按價格訂購。 – xQbert

+0

取決於你想要的東西......'order by new_price + price DESC'' by order by IF(new_price IS NOT NULL,new_price,price)DESC'或者簡單地按一列排序,因爲對我來說它根本沒有意義;) – iRaS

+0

「以某種方式連接價格」是什麼意思? –

回答

1

使用通過合併新價格進行排序,如果存在(不爲空),然後通過價格,如果新的價格是空...

if($order==1) 
{ 
    $order_by='coalesce(Produse.New_price,Produse.Price) ASC'; 
} 
if($order==2) 
{ 
    $order_by='Coalesce(Produse.New_Price,Produse.Price) DESC'; 
}  
if($order==3) 
{ 
    $order_by='Produse.Nume_Prod ASC'; 
} 
if($order==4) 
{ 
    $order_by='Produse.Nume_Prod DESC'; 
} 
if($order==0) 
{ 
    $order_by='Produse.Nume_Prod DESC'; 
} 
     $stmt=$dbh->prepare("Select * FROM Produse 
           INNER JOIN Categorii on Produse.ID_Categorie=Categorii.ID_Categorie 
          where Categorii.Nume_Categ=:id 
          ORDER BY $order_by"); 
     $stmt->bindParam(':id',$id,PDO::PARAM_INT); 
     $stmt->execute(); 
+0

thnx,它的工作:D – chris227