【问题标题】:Using if in a mysql query在 mysql 查询中使用 if
【发布时间】:2012-09-15 23:52:01
【问题描述】:

我已经有这个查询:

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

Obs:dst 是电话号码。

但现在我需要做的是:如果 dst 的第 5 个字符

有可能吗?

这样我得到了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))

【问题讨论】:

    标签: python mysql sql


    【解决方案1】:

    使用 SELECT,您实际上指定了要返回的列集。这个集合可以是简单的列名,也可以是这些列的具体转换,调用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...
    

    等等 :) 关键是要理解,SELECT 实际上并不选择要检索的列,而是定义特定的结果列集,其中一些列在表中,一些列值的子结果转换或字符串,或NULL,或其他。

    【讨论】:

      【解决方案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
      

      【讨论】:

        猜你喜欢
        • 2012-10-12
        • 2013-04-19
        • 1970-01-01
        • 2012-01-16
        • 2021-12-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-16
        相关资源
        最近更新 更多