【问题标题】:doctrine join with MAX()教义加入 MAX()
【发布时间】:2014-10-17 07:37:40
【问题描述】:

我有实体

Template {

   /**
     * @ORM\OneToMany(targetEntity="TemplateSnapshot",  mappedBy="template", cascade={"all"})
     */
    protected $snapshots;

}


/**
 * @ORM\Entity
 */
class TemplateSnapshot {

    /**
     * @ORM\Column(type="datetime")
     * @var \DateTime
     */
    protected $modTime;

}

并尝试在 TemplateSnapshot 中获取按最后一个 modTime 排序的模板

QueryBuilder $query
                    ->leftJoin('EditorBundle:TemplateSnapshot','s','WITH', $tableAlias.'.id = s.template_id')
                    ->groupBy($tableAlias.'.id')
                    ->orderBy('s.modTime','desc')
            ;

我明白了

SELECT t0_.id AS id0, t0_.location AS location1, t0_.name AS name2, t1_.modTime AS modTime3 FROM Template t0_ LEFT JOIN TemplateSnapshot t1_ ON t0_.id = t1_.template_id LEFT JOIN TemplateSnapshot t2_ ON (t0_. id = t2_.template_id) t0_.name 在哪里? GROUP BY t0_.id ORDER BY t2_.modTime DESC LIMIT 20

这将返回第一个连接行。 (第一组然后排序)。我想加入最新的 TemplateSnapshot

其他尝试

$query

                ->leftJoin('TemplateEditorBundle:TemplateSnapshot',
                    's',
                    'WITH',
                    $tableAlias.'.id = s.template_id and s.modTime = MAX(s.modTime)'
                )
                ->groupBy($tableAlias.'.id')
                ->orderBy('s.modTime','desc')
            ;

我明白了:

SELECT t0_.id AS id0, t0_.location AS location1, t0_.name AS name2, t1_.modTime AS modTime3, MAX(t2_.modTime) AS sclr4 FROM Template t0_ LEFT JOIN TemplateSnapshot t1_ ON t0_.id = t1_。 template_id LEFT JOIN TemplateSnapshot t2_ ON (t0_.id = t2_.template_id AND t2_.modTime = MAX(t2_.modTime)) t0_.name 在哪里? ORDER BY t2_.modTime DESC LIMIT 20

和错误

enter code here组函数使用无效

其他想法

我尝试直接查询 TemplateSnapshot

$source = new Entity('TemplateEditorBundle:TemplateSnapshot');

 $query
                   ->orderBy($tableAlias.'.modTime','desc') ->groupBy($tableAlias.'.template_id')
            ;

但它首先是 gorup 然后订购所以不要得到最新的。

【问题讨论】:

  • 你要检索什么?
  • 我想获取由 modDate 订购的具有唯一模板的 TemplateSnapshot。 TemplateSnapshot 有 template_id 行。
  • 每一行都需要Template 数据还是template_id 就足够了?
  • 您需要两个表中的所有数据还是只需要第一或第二列的具体数据?

标签: php symfony doctrine


【解决方案1】:

您需要为此目的实现本机查询。查询应如下所示:

SELECT * FROM TemplateSnapshot ts
INNER JOIN
(SELECT MAX(mod_time) AS mod_time, template_id FROM TemplateSnapshot GROUP BY template_id) AS ts_max
ON ts.template_id = ts_max.template_id AND ts.mod_time = ts_max.mod_time

对于每个Template,此查询将只返回TemplateSnapshot 中最大值为mod_time 的行。

【讨论】:

  • 查询生成器有没有办法做到这一点?
猜你喜欢
  • 2011-03-06
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-28
  • 1970-01-01
  • 1970-01-01
  • 2018-01-30
相关资源
最近更新 更多