4

我有一张post桌子,它的架构是这样的:

CREATE TABLE IF NOT EXISTS `post` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `user_id` bigint(20) DEFAULT NULL,
  `site_id` bigint(20) DEFAULT NULL,
  `parent_id` bigint(20) DEFAULT NULL,
  `title` longtext COLLATE utf8_turkish_ci NOT NULL,
  `status` varchar(20) COLLATE utf8_turkish_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `IDX_5A8A6C8DA76ED395` (`user_id`),
  KEY `IDX_5A8A6C8DF6BD1646` (`site_id`),
  KEY `IDX_5A8A6C8D727ACA70` (`parent_id`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=16620 ;

我正在使用这个 DQL 来获取一个帖子,它是孩子:

$post = $this->_diContainer->wordy_app_doctrine->fetch(
           "SELECT p,c FROM Wordy\Entity\Post p LEFT JOIN p.children c WHERE p.site = :site AND p.id = :id AND p.language = :language AND p.status != 'trashed'  AND c.status != 'trashed' ORDER BY c.title",
           array(
               'params' => array(
               'id' => $id,
               'site' => $this->_currentSite['id'],
               'language' => $this->_currentLanguage->code,
           )
       )
   );

我想做的是:获取一个帖子和所有的孩子。标准是,不包括已删除的帖子或已删除的孩子。

但是当我用一个甚至没有孩子的帖子运行这个查询时,返回的结果集是空的。

当我c.status != 'trashed'从查询中删除部分时,一切正常,但我也会收到垃圾帖子。

提前致谢。

编辑:这是给定 DQL 的 SQL 输出:

SELECT p0_.id AS id0, p0_.title AS title5, p0_.status AS status8, p0_.parent_id AS parent_id9, p1_.id AS id15, p1_.title AS title20, p1_.status AS status23, p1_.parent_id AS parent_id24 FROM post p0_ LEFT JOIN post p1_ ON p0_.id = p1_.parent_id WHERE p0_.site_id = ? AND p0_.id = ? AND p0_.language = ? AND p0_.status <> 'trashed' ORDER BY p1_.title ASC
4

3 回答 3

1

加入后,您的长条件 WHERE 将被“与”在一起,并且没有通过所有检查。将连接内容移到 ON 子句中,并将 c.trashed 检查留在 WHERE 子句中。尝试这样的事情:

SELECT p,c FROM Wordy\Entity\Post p LEFT JOIN children c ON p.site = :site AND p.id = :id AND p.language = :language AND p.status != 'trashed' AND p.id = c.parent_id  WHERE   c.status != 'trashed' ORDER BY c.title
于 2012-07-17T16:33:14.263 回答
1

您忘记了左连接语法ON的子句。

于 2012-07-17T16:34:53.767 回答
1

我想我解决了我自己的问题。

只需with在字段上使用子句join而不是where子句,如下所示:

"SELECT p,c FROM Wordy\Entity\Post p LEFT JOIN p.children c WITH c.status != 'trashed' WHERE p.site = :site........."
于 2012-07-17T16:46:29.600 回答