【问题标题】:ZF2 changing my expression and returning error (Postgre, Distinct)ZF2 更改我的表达式并返回错误(Postgre,Distinct)
【发布时间】:2015-04-29 12:57:09
【问题描述】:

我必须创建一个 SELECT,在其中我将按列 idcontrato 区分行。我用 SQL 做得很好......

SELECT DISTINCT ON (idcontrato) * 
FROM   cad_emprestimo 
WHERE  numerobeneficio = '1135346515'; 

但是当我尝试对 ZF2 做同样的事情时:

$emprestimos = (new EmprestimoTable())->select(function(Select $select) use($cliente) {
        $select->columns([new Expression('DISTINCT ON (idcontrato) *')]);
        $select->where->equalTo('numerobeneficio', $cliente->getBeneficio()->getNumero());
});

我收到以下错误:

SQLSTATE[42601]: Syntax error: 7 ERRO:  erro de sintaxe em ou próximo a "AS"
LINE 1: SELECT DISTINCT ON (idcontrato) * AS Expression1 FROM "cad_e...
                                          ^

ZF2添加的这个'AS Expression1'...我不知道如何删除它。

【问题讨论】:

    标签: php sql postgresql zend-framework2


    【解决方案1】:

    试试下面的代码

    $emprestimos = (new EmprestimoTable())->select(function(Select $select) use($cliente) {
            $select->columns([new Expression('DISTINCT(idcontrato) AS idcontrato'), '*']);
            $select->where->equalTo('numerobeneficio', $cliente->getBeneficio()->getNumero());
    });
    

    【讨论】:

    • 如果我的回答是正确的,那么将其标记为正确,以帮助其他面临同样问题的人。很乐意提供帮助。
    • 我已经尝试过这个解决方案,但它只重新排序按列 idcontrato 分组的结果。我需要隐藏重复的值,并且 DISTINCT ON 仅显示一次如果在其上定义的列值已经显示。 DISTINCT ON (idcontrato) * FROM... 正是我所需要的。还是谢谢你。
    【解决方案2】:

    我发现的明显解决方案是运行原始 SQL:

        $dbAdapter      = GlobalAdapterFeature::getStaticAdapter();
        $numBeneficio   = $cliente->getBeneficio()->getNumero();
        $sqlEmprestimos = "SELECT DISTINCT ON (idcontrato) * FROM cad_emprestimo WHERE numerobeneficio = '".$numBeneficio."'; ";
        $dataSource     = $dbAdapter->createStatement($sqlEmprestimos)->execute();
        $emprestimos    = (new \Zend\Db\ResultSet\ResultSet())->initialize($dataSource);
    

    无论如何,我对此并不满意,这段代码丑得要命。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-27
      • 1970-01-01
      • 2014-07-22
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      相关资源
      最近更新 更多