如何在MySQL查询中使用AND和OR?

时间:2015-06-25 00:30:18

标签: mysql cakephp

我想获取date_last_copied字段为空或小于当前日期的记录。我试过这个,但它没有给我想要的结果:

$tasks = $this->Control->query("
    SELECT *
    FROM
        `controls`
    WHERE
        `owner_id` = ".$user_id."
        AND `control_frequency_id` = ".CONTROL_FREQUENCY_DAILY."
        OR `date_last_copied` = ''
        OR `date_last_copied` < ".  strtotime(Date('Y-m-d'))."
");

3 个答案:

答案 0 :(得分:1)

不确定您的整个逻辑,但您的最终查询语句应该是:

SELECT * FROM `controls` WHERE (`owner_id` = <some owner_id>) 
AND (`control_frequency_id` = <some id value>)
AND (`date_last_copied` = '' OR 
     `date_last_copied` IS NULL OR 
     `date_last_copied` < CURDATE() )

请仔细使用括号来匹配您的逻辑。

答案 1 :(得分:1)

我认为当前的查询看起来像这样。也就是说,找到具有正确owner_id和frequency_id的记录,其中date_last_copied为null或小于某个日期。这个逻辑是否正确?

SELECT *
FROM controls
WHERE owner_id = ::owner_id::
    AND control_frequency_id = ::frequency_id::
    AND (
        date_last_copied IS NULL
        OR date_last_copied < ::date::
    )

但我们应该使用CakePHP查询构建器,而不是运行原始SQL。这个article提供了一些细节。如果我要采取一种解决方案,我们需要以下内容。但我们理想地希望来自CakePHP社区的人在这里发声。编辑:请注意,这似乎只适用于CakePHP 3.0。

// Build the query
$query = TableRegistry::get('controls')
    ->find()
    ->where([
        'owner_id' => $ownerId,
        'control_frequency_id' => $frequencyId,
        'OR' => [
            ['date_last_copied IS' => null],
            ['date_last_copied <' => $date]
        ]
    ]);
// To make sure the query is what we wanted
debug($query);
// To get all the results of the query
foreach ($query as $control) {
    . . .
}

我建议这样做,而不是你上面的原始SQL字符串,因为:

  1. 我们现在可以利用CakePHP的ORM模型。
  2. 我们不必担心您目前容易受到攻击的SQL注入。
  3. 编辑:好的,这是对适用于CakePHP 2.0 ... YMMV

    的语法的猜测
    $controls = $this->controls->find('all', [
        'conditions' => [
            'owner_id' => $ownerId,
            'control_frequency_id' => $frequencyId,
            'OR' => [
                ['date_last_copied IS' => null],
                ['date_last_copied <' => $date]
            ]
        ]
    ];
    

    否则,我们只使用原始查询作为预准备语句:

    $result = $this->getDataSource()->fetchAll("
        SELECT *
        FROM controls
        WHERE owner_id = ?
            AND control_frequency_id = ?
            AND (
                date_last_copied IS NULL
                OR date_last_copied < ?
            )",
        [$ownerId, $frequencyId, $date]
    );
    

答案 2 :(得分:0)

始终指定您用于App的cakePHP版本。

此查询在CakePHP 3.0 for SQL AND和OR中应该可以正常工作。

$query = ModelName>find()
    ->where(['colunm' => 'condition'])
    ->orWhere(['colunm' => 'otherCondition'])
    ->andWhere([
        'colunm' => 'anotherContion',
        'view_count >' => 10
    ])
    ->orWhere(['colunm' => 'moreConditions']);