2012-09-15 18 views
3

我已經有這個疑問:使用如果在一個MySQL查詢

cursor.execute("SELECT calldate, dst, billsec, accountcode, disposition, 
         (billsec/60*%s) as total 
       FROM cdr 
       WHERE calldate >= '%s' and calldate < '%s' 
        and disposition like '%s' and accountcode = '%s' 
        and dst like '%s'" %(rate, start_date, end_date, status, accountcode, destino) 
      ) 

觀測數據:DST是一個電話號碼。

但是現在我需要做的是:如果dst的第5個字符是< = 5,那麼billsec/60 * 0.11總計爲 否則billsec/60 * 0.16。

可能嗎?

這樣,我在MySQL的語法得到了一個錯誤:

cursor.execute("""SELECT calldate, dst, billsec, accountcode, disposition, 
        case when cast(substring(dst,4,1), unsigned) <= 5 then 
          billsec/60*%s as total 
        else 
          billsec/60*%s as total 
        end case 
        FROM cdr where calldate >= '%s' and calldate < '%s' and disposition like '%s' and accountcode = '%s' and dst like '%s'""" %(rate_fixo, rate_movel, start_date, end_date, status, accountcode, destino)) 

回答

2

是的,這是可能的。 Mysql查詢可以包含if語句,只有它們被稱爲case語句,正如其他Piotr Wadas所指出的那樣。

在這裏看到:http://dev.mysql.com/doc/refman/5.0/en/case.html

爲了從一個字符串使用字符串的字符。 http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substr

因此,完整的解決方案會是這樣的:要返回

case when cast(substring(dst,4,1), unsigned) <= 5 then 
    billsec/60*0.11 
else 
    billsec/60*0.16 
end case 
+0

什麼是錯誤陳述? –

2

有了選擇實際指定一組列。這個集合可以是簡單的列名稱,也可以是這些列的特定轉換,調用SQL函數。 「IF」實際上與程序化SQL更相關,在你的例子中你需要一些叫做CASE表達式的東西。 訣竅是由結果CASE表達式設置定義列,這樣

SELECT acol, bcol, ccol, dcol from t1 where ... 

SELECT acol, CASE WHEN sqlfunc_like_substr(someparams,bcol) THEN bcol ELSE some_other_way_modified(bcol) END, ccol, dcol from t1 WHERE ... 

比較不記得此刻CASE確切的語法,但這是這樣的。更多,你可以命名結果列例如。

SELECT acol as uuu, CASE WHEN ... END as mmm, ccol as nnn, dcol as qqq FROM t1 where... 

等等:)的一點是要明白,實際選擇不選擇要檢索列,但定義組特定結果列的,其中一些,因爲它們是在表中,有的列值轉換的子結果或字符串,或者NULL,或者其他。

相關問題