[英]Count Same Values On Mysql Table
我想基于单个字段计算表上的最大值。
我的桌子上有一个image_count字段; 计算的是不同的图像,而不是具有相同图像的不同缩略图。
例如,我有一个名为stack.jpg的图像,并具有三个不同大小的缩略图。
因此,我必须将具有相同image_count的已调整大小的图像保存到db。
让我们给这些文件计数:1。
当我再次上传具有三个缩略图尺寸的另一张图片时; 上传并调整大小的图像必须具有image_count:2。
所以:
ID | Thumbnail | Image | count |
-----------------------------------------------
1 | Small | stack_small.jpg | 1 |
2 | Medium | stack_medium.jpg | 1 |
3 | Big | stack_big.jpg | 1 |
4 | Small | overflw_small.jpg | 2 |
5 | Medium | overflw_medium.jpg | 2 |
6 | Big | overflw_big.jpg | 2 |
-----------------------------------------------
当我想向数据库添加新图像时,计数字段必须为“ 3”。 不是7。
我想按计数分组,但我在使用symfony2与教义,当我尝试使用count获得singleScalarResult时,它抛出异常。
我的代码:
public function countImages($entity_id, $gallery_id)
{
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$count = $qb
->select('COUNT(i)')
->from('CSGalleryBundle:GalleryImage', 'i')
->leftJoin('CSGalleryBundle:Gallery', 'g', 'WITH', 'g.id = i.gallery_id')
->where(
$qb->expr()->eq('i.foreign_key', $entity_id),
$qb->expr()->eq('g.id', $gallery_id)
)
->groupBy('i.image_count')
->setMaxResults(1)
->getQuery()
->getSingleScalarResult();
return $count + 1;
}
错误:
这里有什么问题? 我该如何解决? 有什么更好的方法吗?
谢谢!
您可以使用以下命令更改查询以解决基本问题:
$count = $qb
->select('i')
->from('CSGalleryBundle:GalleryImage', 'i')
->leftJoin('CSGalleryBundle:Gallery', 'g', 'WITH', 'g.id = i.gallery_id')
->where(
$qb->expr()->eq('i.foreign_key', $entity_id),
$qb->expr()->eq('g.id', $gallery_id)
)
->groupBy('i.image_count')
->getQuery()
->getResult();
return count($count);
也许您可以查看“ Doctrine查询生成器文档”以获得更有效的解决方案。
你是对的。 您必须使用主义方式来提高性能。 您可以使用以下查询:
$count = $qb
->select('MAX(i.image_count)')
->from('CSGalleryBundle:GalleryImage', 'i')
->leftJoin('CSGalleryBundle:Gallery', 'g', 'WITH', 'g.id = i.gallery_id')
->where(
$qb->expr()->eq('i.foreign_key', $entity_id),
$qb->expr()->eq('g.id', $gallery_id)
)
->getQuery()
->getSingleScalarResult();
return $count === null ? 1 : $count + 1;
您可以将count方法与
$count = $qb
->select('COUNT(DISTINCT i)')
->from('CSGalleryBundle:GalleryImage', 'i')
->leftJoin('CSGalleryBundle:Gallery', 'g', 'WITH', 'g.id = i.gallery_id')
->where(
$qb->expr()->eq('i.foreign_key', $entity_id),
$qb->expr()->eq('g.id', $gallery_id)
)
->groupBy('i.image_count')
->getQuery()
->getSingleScalarResult();
return $count;
我认为,如果没有匹配的数据,它将引发异常。
只是一个尝试。 我没有检查。 为什么在代码中留下了Join?
$count = $qb
->select('MAX(i.count)')
->from('CSGalleryBundle:GalleryImage', 'i')
->getQuery()
->getSingleScalarResult();
return $count + 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.