我在我的symfony2项目中使用了doctrine。
我有桌子活动和桌子照片。一个活动可以有一张或多张照片,一张照片与一个活动相关。
这是我的一个dql查询:
$dql = "
SELECT e, (e.views * 0.1) + (e.likes * 0.9) as ratingEvent
FROM WevseenMainBundle:Event e
INNER JOIN e.photos p
INNER JOIN e.firstPhoto fp
WHERE fp.date BETWEEN :dateA AND :dateB
AND p.lat BETWEEN :latA AND :latB
AND ( p.lng > :lngA AND p.lng < :lngB )
AND e.status = 'open'
GROUP BY e
HAVING COUNT(p.id) >= :minCountPhotos
ORDER BY ratingEvent DESC
";
$query = $em->createQuery($dql)
->setParameters($parameters)
->setFirstResult($firstEntry) // 0
->setMaxResults($numberOf); // 10
$paginatorEvents = new Paginator($query, true);
有11500个事件和16万张照片,查询非常慢(超过10秒),它来自
GROUP BY e
HAVING COUNT(p.id) >= :minCountPhotos
没有这个,它很快。
我检查了sf2分析器,它说:
SELECT count(DISTINCT e0_.id) AS sclr0 FROM Event e0_ INNER JOIN Photo p1_ ON e0_.id = p1_.event_id INNER JOIN Photo p2_ ON e0_.firstPhoto_id = p2_.id WHERE p2_.date BETWEEN ? AND ? AND p1_.lat BETWEEN ? AND ? AND (p1_.lng > ? AND p1_.lng < ?) AND e0_.status = 'open' GROUP BY e0_.id, e0_.name, e0_.description, e0_.nb_photos, e0_.views, e0_.viewsEventPhotos, e0_.votes, e0_.rating, e0_.likes, e0_.up, e0_.down, e0_.status, e0_.end, e0_.time, e0_.averageTimeEvent, e0_.averageTimePhotos, e0_.averageTimeEventAndPhotos, e0_.needInstagramUpdate, e0_.origin, e0_.featured, e0_.firstPhoto_id HAVING COUNT(p1_.id) >= ?
Parameters: [Object(DateTime), Object(DateTime), '-42.93442389074508', '73.48078267112892', '-180', '180', '2']
Time: 2029.33 ms
SELECT DISTINCT e0_.id AS id0, e0_.views * 1 + e0_.likes * 0 AS sclr1 FROM Event e0_
INNER JOIN Photo p1_ ON e0_.id = p1_.event_id INNER JOIN Photo p2_ ON e0_.firstPhoto_id = p2_.id WHERE p2_.date BETWEEN ? AND ? AND p1_.lat BETWEEN ? AND ? AND (p1_.lng > ? AND p1_.lng < ?) AND e0_.status = 'open' GROUP BY e0_.id, e0_.name, e0_.description, e0_.nb_photos, e0_.views, e0_.viewsEventPhotos, e0_.votes, e0_.rating, e0_.likes, e0_.up, e0_.down, e0_.status, e0_.end, e0_.time, e0_.averageTimeEvent, e0_.averageTimePhotos, e0_.averageTimeEventAndPhotos, e0_.needInstagramUpdate, e0_.origin, e0_.featured, e0_.firstPhoto_id HAVING COUNT(p1_.id) >= ? ORDER BY sclr1 DESC LIMIT 10 OFFSET 0
Time: 6179.01 ms
这两个需要时间的查询。 我怎样才能改善这个?
更新,解决方案:
改变
GROUP BY e
与
GROUP BY e.id
答案 0 :(得分:1)
只有在对分页器进行迭代时才会执行您的请求。 您应该复制已翻译的SQL请求并将其配置在Doctrine之外,可能需要8秒才能执行。一旦你向表中添加一些明智选择的索引,它的可能性就会快得多。