在Zend Framework 2的SQL查询中使用case / when / then

时间:2013-11-26 09:37:42

标签: sql zend-framework2 zend-db

我有疑问:

SELECT user_name, group_id,
       CASE WHEN col_1 = 1 THEN 0 
            WHEN col_2 = 1 THEN 1 
            WHEN col_3 = 1 THEN 2 
       END as merge_col
FROM some_table
WHERE group_id = 10
ORDER BY merge_col.

如何使用 ZF2 Zend \ .. \ Sql ,我可以实现此查询吗?

更新

感谢谁试图帮助我。它的工作如下:

$select->columns(array(
            'user_name', 
            'group_id', 
            'merge_col' => new Expression('CASE WHEN col_1 = 1 THEN 0 
                     WHEN col_2 = 1 THEN 1 
                     WHEN col_3 = 1 THEN 2 END')))
->where (array('group_id'=> 10))
->order ('merge_col');

有更好的答案吗?

感谢。

3 个答案:

答案 0 :(得分:5)

$select = $sql->select ('some_table');
$select->columns(array(
            new Expression('CASE WHEN col_1 = 1 THEN 0 
                     WHEN col_2 = 1 THEN 1 
                     WHEN col_3 = 1 THEN 2 
                         END AS merge_col'), 'user_name', 'group_id'))
->where ('group_id = 10')
->order ('merge_col');

答案 1 :(得分:2)

以下是使用参数化解决问题的更好方法。您更新的答案解决了我的问题,但后来我通过参数化改进了它。

$case = 'CASE ';
$sqlCase = $this->getAdapter();
$case .= $sqlCase->quoteInto('WHEN col_1 = 1 THEN ? ', yourVariable, Zend_Db::INT_TYPE);
$case .= $sqlCase->quoteInto('WHEN col_2 = 1 THEN ? ', yourVariable, Zend_Db::INT_TYPE);
$case .= $sqlCase->quoteInto('WHEN col_2 = 1 THEN ? ', yourVariable, Zend_Db::INT_TYPE);
$case .= 'ELSE 0 END ';


以下是您的其余代码。只需查看我在上面的代码中生成的$case变量。为什么$case是字符串?因为Zend_Db_Expr需要String值。

$select =$this->getAdapter();
$select->columns(array(
            'user_name', 
            'group_id', 
            'merge_col' => new Zend_Db_Expr($case)))
       ->where (array('group_id'=> 10))
       ->order ('merge_col');

答案 2 :(得分:0)

使用Zend \ Db \ Sql \ Expression:

    use Zend\Db\Sql;
    ....

    $sql = $this->tableGateway->getSql();
    $select = $sql->select();
    $select->columns(array('user_name', 'group_id',
            new Sql\Expression('CASE WHEN col_1 = 1 THEN 0 
                     WHEN col_2 = 1 THEN 1 
                     WHEN col_3 = 1 THEN 2 
                         END as merge_col')));

    return $this->tableGateway->selectWith($select);