cakephp 2.x 在子查询中使用 'NOT IN'

cakephp 2.x using 'NOT IN' in subquery

我有这个小 mysql 查询(它 returns 元素没有 1,3,5 状态):

SELECT DISTINCT number FROM records WHERE number NOT IN
( SELECT number FROM records WHERE state_id = 1 or state_id = 3 or state_id = 5)

在 cakephp 中,我不擅长子查询,但我能够做到:

    $conditionsSubQuery['`Record2`.`state_id`'] = array(1,3,5);

      $db = $this->Record->State->getDataSource();

      $subQuery = $db->buildStatement(
    array(
        'fields'     => array('`Record2`.`number`'),
        'table'      => $db->fullTableName($this->Record),
        'alias'      => 'Record2',
        'limit'      => null,
        'offset'     => null,
        'joins'      => array(),
        'conditions' => $conditionsSubQuery,
        'order'      => null,
        'group'      => null
    ),
    $this->Record
);

      $subQuery = ' `Record`.`number` NOT IN (' . $subQuery . ') ';

      $subQueryExpression = $db->expression($subQuery);

     $conditions[] = $subQueryExpression;



     $subQuery=$this->Record->find('first', compact('conditions'),
             //array('recursive'=>0),
             array('fields'=>array('Record.state_id')
             ));

也许我不明白一些好东西,但获得相同的结果真的很烦人需要大量的代码,我知道有 $this->query for core mysql 但是在 find 中有没有一种方法可以通过正确使用 'conditions' 来获得相同的结果?或者 cakephp 不支持 'NOT IN',这就是为什么没有更简单的方法?

更新1: 查询方案如下:

(1, 'A', 1),
(2, 'A', 2),
(3, 'B', 3),
(4, 'C', 2),
(5, 'B', 1),

mysql查询的结果只检索到 C,因为 B 也有与 A 相同的值 3,1。 如果没有 'not in' B 也会返回(因为也有 1 个值)。

我试着让它尽可能清楚,我添加了一些额外的值来显示哪个适合结果: http://www.sqlfiddle.com/#!9/cc92a/1

除非我误解了您的原始查询,否则您根本不需要为此使用子查询。

在 CakePHP 中,您可以在查找条件中使用关键字 NOT 来应用查询的 NOT 部分;处理 IN 部分只需传递一个选项数组:-

$this->Record->find(
    'all',
    array(
        'fields' => array(
            'number'
        )
        'conditions' => array(
            'NOT' => array(
                'state_id' => array(1, 3, 5)
            )
        ),
        'group' => array(
            'number'
        )
    )
);

我使用 fields 将响应限制为仅 number 列,并使用 group 仅 return 独特的结果。

否则,要在 Cake 2 中使用子查询,最简单的方法是单独执行子查询,然后在主查询中使用该响应。 Cake 3 的新 ORM 可以更好地设置子查询。

更新:

根据您在问题中更新的示例,我认为实现您希望它执行两个查询的最简单方法。首先获取您不想包含的记录编号 ($exclude),然后使用该结果将它们从您的结果查询中排除:-

$exclude = $this->Record->find(
    'list',
    array(
        'fields' => array(
            'id', 'number'
        ),
        'conditions' => array(
            'state_id' => array(1, 3, 5)
        ),
        'group' => array(
            'number'
        )
    )
);

$result = $this->Record->find(
    'all',
    array(
        'fields' => array(
            'number'
        )
        'conditions' => array(
            'NOT' => array(
                'number' => $exclude
            )
        ),
        'group' => array(
            'number'
        )
    )
);
$coupons = $this->Record->find('list',
    array('conditions'=>('Record.id NOT IN (select record_id from record_2)')
));

这就是我所做的。 希望对你有帮助。