我可以在Zend 2的JOIN语句中使用WHERE子句吗?

时间:2015-08-04 09:24:01

标签: php zend-framework2

我有一个普通的SQL语句,它从数据库中返回15条记录。如果我尝试使用Zend 2复制相同的东西,它会返回9条记录。区别在于其中一个JOIN中的WHERE / Conditional语句。 让我解释一下......

这是一个实际的SQL查询:

SELECT FROM 
   BLABLA AS B (some other joins and then..)

       LEFT JOIN
   CITY AS C ON C.SERVICE_ID = B.SERVICE_ID
                AND C.DELETED = FALSE
   WHERE
       (B.PRODUCT_ID = 2219)
          AND (B.DELETED = FALSE);

如您所见,JOIN语句中有一个WHERE / Conditional(AND C.DELETED = FALSE)子句,我想在Zend 2 DB select中执行相同的操作。

所以我这样做:

$select = $sql->select(); // This is Zend 2's select()

$select->from(
            ['B' => 'BLABLA']
        )

        ->columns(
            [
                'VALUE',
                'NOTES',
                'SERVICE_ID'
            ]
        )


        ->join(
            ['C' => 'CITY'],
            'C.SERVICE_ID = B.SERVICE_ID',
            'left'
        )

        ->where('C.DELETED = FALSE') // If I remove this line, it returns 15 records just like that plain SQL query, however doing so I lose this conditional statement. If I don't remove it, it returns 9 records.
        ->where('B.DELETED = FALSE')
        ->where('B.PRODUCT_ID = 2219');

我做错了什么? :(

2 个答案:

答案 0 :(得分:0)

请尝试以下ZEND SQL代码。

$select = $sql->select(); // This is Zend 2's select()

$select->from(
            ['B' => 'BLABLA']
        )

        ->columns(
            [
                'VALUE',
                'NOTES',
                'SERVICE_ID'
            ]
        )


        ->join(
            ['C' => 'CITY'],
            'C.SERVICE_ID = B.SERVICE_ID AND C.DELETED = FALSE',
            'left'
        )
        ->where('B.DELETED = FALSE')
        ->where('B.PRODUCT_ID = 2219');

答案 1 :(得分:0)

解决了它。

显然你需要用表达式包装这些东西。所以在我的情况下:

->join(
     ['C' => 'CITY'],
     new \Zend\Db\Sql\Expression('C.SERVICE_ID = B.SERVICE_ID AND C.DELETED = FALSE'),
     'left'
)