使用Cakephp 2.x选择id不在另一个表中的所有记录

时间:2017-08-09 10:18:56

标签: php mysql cakephp cakephp-2.0

你好我想在我的查询中实现OR条件,它将从另一个不存在id的表中获取所有记录OR获取最近24小时内插入的记录。

此查询为我提供了最近24小时的结果

        $this->Behaviors->attach('Containable');
        return $this->find('all', array(

            'contain' => array(
              'User','UserInfo','QuestionAndTopic.Topic','UpVoteQuestion','Answer'

            ),
             'conditions' => array(
                'Question.created >=' => date('Y-m-d H:i:s', strtotime('-24 hour'))

            ),

            'order' => 'Question.question_id DESC',
            'recursive' => 0
        ));

我想做这样的事情

$this->Behaviors->attach('Containable');
return $this->find('all', array(

    'contain' => array(
      'User','UserInfo','QuestionAndTopic.Topic','UpVoteQuestion','Answer'

    ),
     'conditions' => array(
         'OR' => array(
    array( 'Question.created >=' => date('Y-m-d H:i:s', strtotime('-24 hour'))),
    array('Question.question_id NOT IN ' => 'Answers'),// get results where question id is not present in answers table as foreign key
)



    ),

    'order' => 'Question.question_id DESC',
    'recursive' => 0
));

我希望你理解我的问题

1 个答案:

答案 0 :(得分:0)

有几种方法可以做到这一点。

1) 您可以使用左连接并检查没有答案的位置。

在SQL中:

select * 
from questions 
left join answers on questions.id = answers.question_id
where answers.id is null;

在CakePHP中:

$this->find('all', array(
    'contain' => array(
        'User','UserInfo','QuestionAndTopic.Topic','UpVoteQuestion','Answer'
    ),
   'conditions' => array(
       'OR' => array(
           array( 'Question.created >=' => date('Y-m-d H:i:s', strtotime('-24 hour'))),
           array('Answer.id is null'),// get results where question id is not present in answers table as foreign key
       )
    ),
    'order' => 'Question.question_id DESC',
    'recursive' => 0
));

2)

您可以使用子查询在答案表中加载问题ID列表,并使用基本not in来获取补充集。

在SQL中:

select * from questions where id not in (select distinct question_id from answers);

在CakePHP中:

cakephp中的子查询有点复杂。首先必须设置子查询,然后在查询中调用它。见https://book.cakephp.org/2.0/en/models/retrieving-your-data.html#sub-queries

我从未尝试在条件中使用子查询,但我认为这应该有用。

$db = $this->getDataSource();
$subquery = $db->buildStatement(
    array(
        'table' => 'answers',
        'alias' => 'Answer',
        'fields' => 'question_id'
    ),
    $this
);
$this->find('all', array(
    'contain' => array(
        'User','UserInfo','QuestionAndTopic.Topic','UpVoteQuestion','Answer'
    ),
   'conditions' => array(
       'OR' => array(
           array( 'Question.created >=' => date('Y-m-d H:i:s', strtotime('-24 hour'))),
           array('Question.question_id NOT IN ' => '($subquery)'),// get results where question id is not present in answers table as foreign key
       )
    ),
    'order' => 'Question.question_id DESC',
    'recursive' => 0
));