我正在尝试将这个我认为简单的 mysql 查询转换为 Doctrine dql,但是,我现在经历了相当大的挣扎......
SELECT (c.prix-aggregates.AVG) AS test
FROM immobilier_ad_blank c
CROSS JOIN (
SELECT AVG(prix) AS AVG
FROM immobilier_ad_blank)
AS aggregates
这样做的目的:创建 z-score。
来自这个问题的原始实现 Calculating Z-Score for each row in MySQL? (simple)
我想过在实体内创建一个关联,但我的意思是它没有必要,它仅用于统计数据。
编辑:顺便说一句,我不想使用原始 SQL,我将使用
getDQL
从另一个查询构建器表达式中提取“子查询”。否则,我将不得不重写我的动态查询构建器以考虑 rawSQL。编辑2:
试过这个
$subQb = $this->_em->createQueryBuilder();
$subQb->addSelect("AVG(subC.prix) as AMEAN")
->from("MomoaIntegrationBundle:sources\Common", "subC");
$subDql = $subQb->getDQL();
$dql = "SELECT c.prix FROM MomoaIntegrationBundle:sources\Common c INNER JOIN ($subDql) AS aggregates";
原始 dql 是:
SELECT c.prix FROM MomoaIntegrationBundle:sources\Common c INNER JOIN (SELECT AVG(subC.prix) as AMEAN FROM MomoaIntegrationBundle:sources\Common subC) AS aggregates
收到这个奇怪的错误:
line 0, col 70 near '(SELECT AVG(subC.prix)': Error: Class '(' is not defined.
编辑3:
我发现了一种使其工作的强硬方式,但学说对实体的实现很顽固,并且忘记了统计不需要实体!
$subQb = $this->_em->createQueryBuilder();
$subQb->addSelect("AVG(subC.prix) as AMEAN")
->from("MomoaIntegrationBundle:sources\Common", "subC");
$sql = "SELECT (c.prix-aggregates.sclr_0) AS test FROM immobilier_ad_blank c CROSS JOIN "
. "({$subQb->getQuery()->getSQL()}) AS aggregates";
$stm = $stm = $this->_em->getConnection()->prepare($sql);
$stm->execute();
$data = $stm->fetchAll();
如果你有更好的解决方案,我全神贯注!我实际上不喜欢这个解决方案。
最佳答案
对于复杂的查询,您可能需要考虑绕过 DQL 并使用 native 查询 - 特别是因为您不需要实体中的结果。
$connection = $em->getConnection();
$statement = $connection->prepare("
select c.prix-aggregates, t1.avg
from immobilier_ad_blank
cross join (
select avg(prix) as avg
from immobilier_ad_blank
) t1
");
$statement->execute();
$results = $statement->fetchAll();
关于php - 交叉连接到 DQL,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31766505/