2016-01-18 146 views
0

我想使用,如果在SQL查詢語句:使用,如果在MySQL查詢語句

我想要什麼:

if(tractions_delivery.send_date_id !=0){ 

      date_send_commodities.id = tractions_delivery.send_date_id 
} 

我的查詢:

 from 

      tractions_delivery,user_address,province,city,date_send_commodities,users 

     WHERE 

     tractions_delivery.tr_id = $tr_id 
     AND 
     tractions_delivery.address_id = user_address.id 
     AND 
     user_address.province_id = province.id 
     AND 
     user_address.city_id  = city.id 
     AND 
     //not work 
     (tractions_delivery.send_date_id IS NOT 0 date_send_commodities.id = tractions_delivery.send_date_id) 

     AND 
     users.id = user_address.user_id 
+0

你能澄清一下這個查詢是應該做的嗎? – Mureinik

+2

... AND CASE WHEN tractions_delivery.send_date_id!= 0 THEN date_send_commodities.id = tractions_delivery.send_date_id ELSE 1 = 1 END AND users.id = user_address.user_id – iiro

+0

什麼是「不是0」?你可以寫'IS NOT NULL'或'<> 0'。 – i486

回答

1

你可以使用CASE語句

SELECT 
* 
FROM 
tractions_delivery, 
user_address, 
province, 
city, 
date_send_commodities,users 
WHERE 
tractions_delivery.tr_id = $tr_id AND 
tractions_delivery.address_id = user_address.id AND 
user_address.province_id = province.id AND 
user_address.city_id = city.id AND 
CASE WHEN tractions_delivery.send_date_id != 0 THEN date_send_commodities.id = tractions_delivery.send_date_id ELSE 1=1 END AND 
users.id = user_address.user_id 
1

你可以僅在存儲過程或函數中使用if語句。如果你只是寫了一條sql語句,不幸的是你不能在查詢周圍使用if語句。但是你可以在查詢本身,例如:

SELECT CASE WHEN col1 = col2 THEN'col1 equals col2' else 'col1 doesnt equal col2' ELSE 
FROM table1 

所以各地不起作用使用邏輯,但在字段列表中,您可以創建CASE WHEN ELSE END邏輯。

1

CASEIF()運營商可以提供幫助。

實例,

SELECT (CASE 1 WHEN 1 THEN 'One' WHEN 2 THEN 'Two' ELSE 'More' END) 'Result'; 

OR

SELECT IF(1=1, 'One', 'Two') 'Result'; 

這些CASEIF()運營商可以在SELECT子句中使用有條件地解釋列值和在結果返回。

注意:不要將CASE運算符與'CASE條件語法塊'混淆,結尾爲END CASE