Postgresql 将排除添加到联接中的条令查询生成器
我在Symfony应用程序中使用条令查询生成器构建了以下查询Postgresql 将排除添加到联接中的条令查询生成器,postgresql,symfony,join,doctrine,dql,Postgresql,Symfony,Join,Doctrine,Dql,我在Symfony应用程序中使用条令查询生成器构建了以下查询 $qb->select('c') ->from('AppBundle:Course', 'c') ->join('AppBundle:Log', 'a', Expr\Join::WITH, $qb->expr()->eq('c.id', 'a.course')) ->where($qb->expr()->in('a.type', '
$qb->select('c')
->from('AppBundle:Course', 'c')
->join('AppBundle:Log', 'a', Expr\Join::WITH, $qb->expr()->eq('c.id', 'a.course'))
->where($qb->expr()->in('a.type', ':type'))
->andWhere($qb->expr()->between('a.time', ':start', ':end'))
->andWhere($qb->expr()->eq('c.status', ':status'))
->setParameter(':type', ['opened'])
->setParameter(':standardScratchScore', [74])
->setParameter(':status', Course::OPENED)
->setParameter(':start', $dateFrom->format('Y-m-d H:i:s'))
->setParameter(':end', $dateTo->format('Y-m-d H:i:s'))
;
在我的代码中,我对课程进行了迭代,然后再次查询日志表,以检查课程中不存在特定类型的条目。是否有一种方法可以将本课程的log.type='log.sent email'排除在初始查询中,而不使用类似于子选择的内容
在循环中再次查询同一个表对我来说是次优的,NewRelic认为这会损害我的应用程序的性能 您可以根据这一特定需求再次加入表格:
$qb->select('c')
->from('AppBundle:Course', 'c')
->join('AppBundle:Log', 'a', Expr\Join::WITH, $qb->expr()->eq('c.id', 'a.course'))
->leftjoin(
'AppBundle:Log',
'b',
Expr\Join::WITH,
$qb->expr()->andx(
$qb->expr()->eq('c.id', 'b.course'),
$qb->expr()->eq('b.type', 'log.sent-email')
))
) // join log a second time, with the type condition
->where($qb->expr()->in('a.type', ':type'))
->andWhere($qb->expr()->between('a.time', ':start', ':end'))
->andWhere($qb->expr()->eq('c.status', ':status'))
->andWhere($qb->expr()->isNull('b.type')) // Only select records where no log record is found
->setParameter(':type', ['opened'])
->setParameter(':standardScratchScore', [74])
->setParameter(':status', Course::OPENED)
->setParameter(':start', $dateFrom->format('Y-m-d H:i:s'))
->setParameter(':end', $dateTo->format('Y-m-d H:i:s'))
;
您是否尝试过左连接,连接结果为空?类似于:LEFT JOIN log with log.type='log.sent email',其中log.id为NULL@Jeroen谢谢你的评论。我不确定这是否合适,因为我已经加入课程并登录课程。id=log.course\u id。我认为您使用IS NULL的行是正确的,但这是我遇到的额外类型筛选器。我想我接受这一答案是迫不及待的。很抱歉。我发现leftjoin b在该表中的所有log.sent-email条目上都加入,而不仅仅是在第一次加入的结果集上。我不确定我现在做错了什么…@crmpicco你是对的,我之前关于不需要在连接中指定外键的声明不正确,因为这是一对多连接。更新了我的答案,你能查一下吗?这是未经测试的。你是明星,伙计!我花了太长时间看这个。谢谢你的帮助。