简体   繁体   English

在一个查询中计算多个记录计数

[英]counting multiple number of record counts in one query

    SELECT li.listing_id, li.title, p.name, c.comment, COUNT( * ) AS pic_count
    FROM listings li
    LEFT JOIN photos p ON li.listing_id = p.listing_id
    LEFT JOIN comments c ON li.listing_id = c.listing_id
    WHERE li.listing_id =1
    GROUP BY li.listing_id
    LIMIT 1;

above query gives me the count of photos for given listing_id, same way i want the count of comments for that listing_id in same query, is that possible ? 上面的查询为我提供了给定listing_id的照片数量,以同样的方式,我希望在同一查询中为该listing_id的评论数量,这可能吗? 2 counts in one query .. 一个查询中有2个计数

Your count is wrong. 你算错了。 p.name should not be in the field list if you want to group by listing. 如果要按列表分组,则p.name不应在字段列表中。 But even without it, you get 1 for listings without a photo, because of the * in count. 但是即使没有它,由于计数* ,您也会在没有照片的情况下获得1的列表。

If your foto's got a unique id, you can do this: 如果您的照片具有唯一的ID,则可以执行以下操作:

SELECT li.listing_id, li.title,
  COUNT(DISTINCT p.photo_id) as photo_count,
  COUNT(DISTINCT c.comment_id) as comment_count
FROM listings li
  LEFT JOIN photos p ON li.listing_id = p.listing_id
  LEFT JOIN comments c ON li.listing_id = c.listing_id
WHERE li.listing_id =1
GROUP BY li.listing_id
LIMIT 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM