php - 使用 union 创建 zf2 查询 'not in' 子句

标签 php mysql zend-framework2

我想使用联合查询结果 Not in在ZF2中。将返回该查询的结果

Query: $selectLevelTwoPointFive->combine($selectLevelAll, 'UNION');
Result: ( SELECT `assigned`.`item_id` AS `item_id` FROM `assign_items_level_twopointfive` AS `assigned` ) UNION ( SELECT `assigned`.`item_id` AS `item_id` FROM `assign_items` AS `assigned` )

现在我想在“not in”子句中使用此查询的结果。

$select = $sql->select()->from(array(
                    "items" => "cu_items"
            ))->columns(array('item_name'=>  new \Zend\Db\Sql\Expression(" group_concat(`items`.`item_name`)") ));            

            $select->join(array(
                "ca" => "cu_areas"
            ), new Expression(" ca.area_id = items.area_id ")
             , array(
                'area_name'
            ), $selectLevelAll::JOIN_INNER);
 $select->where->addPredicate(new \Zend\Db\Sql\Predicate\Expression('items.item_id NOT IN (?)',
                            array($selectLevelTwoPointFive)));

结果是:

SELECT group_concat(`items`.`item_name`) AS `item_name`, `ca`.`area_name` AS `area_name` FROM `cu_items` AS `items` INNER JOIN `cu_areas` AS `ca` ON ca.area_id = items.area_id WHERE `items`.`is_opted` = 'yes' AND `ca`.`is_opted` = 'yes' AND items.item_id NOT IN ((( SELECT `assigned`.`item_id` AS `item_id` FROM `assign_items_level_twopointfive` AS `assigned` ) UNION ( SELECT `assigned`.`item_id` AS `item_id` FROM `assign_items` AS `assigned` )))

它显示 mysql 错误: Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION ( SELECT已分配. item_id AS item_id FROM分配项目AS受让人'位于第 1 行`

我需要的查询是:

SELECT group_concat(items.item_name) AS item_name, ca.area_name AS area_name FROM cu_items
 AS items INNER JOIN cu_areas AS ca ON ca.area_id = items.area_id
 WHERE items.is_opted = 'yes' AND ca.is_opted = 'yes' AND items.item_id NOT IN 
(
    (
        SELECT assigned.item_id AS item_id FROM assign_items_level_twopointfive AS assigned  
        UNION ( SELECT assigned.item_id AS item_id FROM assign_items AS assigned )
    )
)

实际上,当我使用combine()时,它会添加圆括号(第一个查询)并集(第二个查询)但是in not我需要第一个查询联合第二个查询。

请帮忙。如果有人建议mysql改变它也可以。

最佳答案

感谢上帝,找到该页面。 我们需要重写setSpecification() 这是答案的链接。 we can override the query output

关于php - 使用 union 创建 zf2 查询 'not in' 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36905594/

相关文章:

php - Zend 框架 2 单选按钮

php - 根据表数据有条件地执行SQ​​L查询/语句

PHP-你如何拆分一组不同的行,这些行被放在一起?

mysql - Sequelize : multiple where clause

php - MYSQL 为最后 5 条不同的记录选择 5 条记录

linux - Xampp 无法在 Linux 上运行

php - htmlentities 正在破坏超链接

php - 如何在codeigniter中将csv文件导入到mysql

mysql - 如何在MySql存储过程的一个select语句中选择多个avg(列)?

doctrine-orm - 教义分页器