与Zend一起使用Mysql CASE语句

时间:2012-07-27 01:54:28

标签: mysql zend-framework case

我有以下查询从数据库中选择一些记录:

$select_person = $this->select()
        ->setIntegrityCheck(false)
        ->from(array('a' => 'tableA'), 
                array(new Zend_Db_Expr('SQL_CALC_FOUND_ROWS a.id'),
                        'a.cid',  
                        'a.email',
                        'final' => new Zend_Db_Expr( "concat( '<div 
                            style=\"color:#1569C7; font-weight:bold\">',
                            a.head , ' ' ,  a.tail,  '</div>')" ),
                        'a.red_flag'
                )
        )   
        ->joinLeft(array('b' => 'tableb'), ... blah blah)
        ->where('blah blah')
        ->order('a.head ASC')

我想修改上面的查询,以便为'final'选择不同的值,具体取决于

的值
a.red_flag.

可以包含值 - true或false。

我知道我可以使用mysql的CASE语句 - 例如以下内容:

'final' => new Zend_Db_Expr("CASE a.red_flag WHEN 'true' THEN '$concatstr1'
                        ELSE '$concatstr2' END")

$concatstr1 = "concat( '<div style=\"color:red; font-weight:bold\">', a.head , ' ' , a.tail, '</div>')" ;

的值

$concatstr2 = "concat( '<div style=\"color:blue; font-weight:bold\">', a.head , ' ' , a.tail, '</div>')" ;

的值

但是,它会抛出错误

  

消息:SQLSTATE [42000]:语法错误或访问冲突:1064   您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'div                         style =“color:red; font-weight:bold”&gt;',                             a.head,'','在第1行

如何使此查询有效? 非常感谢任何帮助。

由于

2 个答案:

答案 0 :(得分:3)

Personnaly,我不喜欢将HTML作为DB的答案。之后调试和更改会让人感到困惑和困难。此外,由于与'和'的混淆以及MySQL中的所有保留字符(&lt;,&gt;,;,...),您可能会遇到一些错误我建议你试试这个:

'final' => new Zend_Db_Expr("CASE a.red_flag WHEN 'true' THEN 1
                        ELSE 0 END")

然后检查a.red_flag的值;

if($this->final) {
    $output .= '<div style=\"color:red; font-weight:bold\">';
} else {
    $output .= '<div style=\"color:blue; font-weight:bold\">';
}
$output .= $this->head.' '.$this->tail;
$output .= '</div>';

如果查询仍无效。尝试

echo $select->__toString; exit();

并检查查询。尝试使用数据库中的__toString获得的输出,并检查它是否有效。以这种方式修复它更容易。你也可以在这里显示查询字符串,它将更容易调试。

答案 1 :(得分:1)

最后,我在声明中发现了错误。 罪魁祸首是 - 我在$concatstr1语句中的$concatstr2$select_person中使用了引号。 正确的查询应该如下形成:

$select_person = $this->select()
        ->setIntegrityCheck(false)
        ->from(array('a' => 'tableA'), 
                array(new Zend_Db_Expr('SQL_CALC_FOUND_ROWS a.id'),
                        'a.cid',  
                        'a.email',
                        final' => new Zend_Db_Expr("CASE a.red_flag WHEN 'true' THEN $concatstr1 ELSE $concatstr2 END"),
                        'a.red_flag'
                )
        )   
        ->joinLeft(array('b' => 'tableb'), ... blah blah)
        ->where('blah blah')
        ->order('a.head ASC');

finalconcatstr1时,现在返回“red_flag” - true的适当值,否则它会返回concatstr2

相关问题