[英]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.