Doctrine DQL - 如何 select 仅来自数据集的唯一记录
Doctrine DQL - how to select only unique records from the dataset
我的任务是从数据库中选择一个品牌和该品牌订单价值最高的客户(连同订单价值)。
我想出了这个查询:
$ordersQuery = $em->createQuery(
"SELECT b.name AS brand, c.name, MAX(DISTINCT o.value) AS total
FROM AppBundle:VOrder o
LEFT JOIN o.brand b
LEFT JOIN o.customer c
GROUP BY b.id, c.id"
);
查询的结果是这样的记录:
Brand #1 ( Customer #5 - 7.00 )
Brand #1 ( Customer #27 - 35.00 )
Brand #1 ( Customer #32 - 169.00 )
Brand #1 ( Customer #38 - 101.00 )
Brand #2 ( Customer #334 - 21.00 )
Brand #2 ( Customer #344 - 61.00 )
Brand #2 ( Customer #364 - 159.00 )
Brand #2 ( Customer #427 - 170.00 )
如您所见,每个品牌都有很多记录。
如何修改我的查询,以便只显示每个品牌(以及客户)的最高订单价值的一条记录?
我认为无法使用 DQL 执行它,但您可以像这样执行原始查询:
SELECT t1.maxvalue, b.name AS brand, c.name
FROM VOrder o
JOIN (
SELECT MAX(DISTINCT value) as maxvalue, brandId
FROM VOrder
GROUP BY brandId
) as t1 ON (o.value = maxvalue AND o.brandId = t1.brandId)
LEFT JOIN brand b ON (...)
LEFT JOIN customer c ON (...)
您可以使用 new Doctrine_RawSql()
构建它。
使用示例:Doctrine - subquery in from
我的任务是从数据库中选择一个品牌和该品牌订单价值最高的客户(连同订单价值)。
我想出了这个查询:
$ordersQuery = $em->createQuery(
"SELECT b.name AS brand, c.name, MAX(DISTINCT o.value) AS total
FROM AppBundle:VOrder o
LEFT JOIN o.brand b
LEFT JOIN o.customer c
GROUP BY b.id, c.id"
);
查询的结果是这样的记录:
Brand #1 ( Customer #5 - 7.00 )
Brand #1 ( Customer #27 - 35.00 )
Brand #1 ( Customer #32 - 169.00 )
Brand #1 ( Customer #38 - 101.00 )
Brand #2 ( Customer #334 - 21.00 )
Brand #2 ( Customer #344 - 61.00 )
Brand #2 ( Customer #364 - 159.00 )
Brand #2 ( Customer #427 - 170.00 )
如您所见,每个品牌都有很多记录。
如何修改我的查询,以便只显示每个品牌(以及客户)的最高订单价值的一条记录?
我认为无法使用 DQL 执行它,但您可以像这样执行原始查询:
SELECT t1.maxvalue, b.name AS brand, c.name
FROM VOrder o
JOIN (
SELECT MAX(DISTINCT value) as maxvalue, brandId
FROM VOrder
GROUP BY brandId
) as t1 ON (o.value = maxvalue AND o.brandId = t1.brandId)
LEFT JOIN brand b ON (...)
LEFT JOIN customer c ON (...)
您可以使用 new Doctrine_RawSql()
构建它。
使用示例:Doctrine - subquery in from