使用WHERE IN时如何获取每个项目的计数

时间:2015-05-09 07:00:21

标签: php mysql

我有一个表评论 enter image description here

我正在查询

SELECT * FROM comment WHERE coupon_id IN (28,14,56);

我想选择每张优惠券的所有评论和评论总数 [优惠券ID为(28,14,56)]

请查看SQLFiddle Showing the Query

2 个答案:

答案 0 :(得分:3)

  

我想选择每张优惠券的评论总数[优惠券ID为(28,14,56)]

您需要使用GROUP BY

SELECT
    coupon_id,
    COUNT(*)
FROM
    comment
WHERE
    coupon_id IN (28,14,56)
GROUP BY
    coupon_id;

如果您想获得评论的数量以及所有评论,您必须使用子查询:

SELECT 
    *,
    (SELECT 
           COUNT(*) 
     FROM 
          `comment` AS cnt_comment 
     WHERE 
          cnt_comment.coupon_id=comment.coupon_id
    ) AS total_comments
FROM 
     `comment` 
WHERE 
     coupon_id IN (28,14);

sqlfiddle

答案 1 :(得分:1)

使用GROUP BY。试试 -

SELECT 
    *, COUNT(comment_id) AS total_comment 
FROM comment 
WHERE coupon_id IN (28,14,56) 
GROUP BY coupon_id 

如果您不想要所有列并指定所需的列,请删除*