MySQL 中使用 GROUP BY 对后分组的数据进行 COUNT() 统计
SELECT id,title FROM tb_item GROUP BY id


SELECT id,title,count(*) AS counter FROM tb_item GROUP BY id

counter 实际上是每组的计数


统计分组后的数据,应该使用这样的子查询:

select count(*) from (select count(*) FROM service GROUP BY name,service) t


实例:

var replacements = {tags:"11,12,13"}
var sql = `
    SELECT id,tags,title,r.* FROM tb_item AS i
    LEFT JOIN tb_item_tag_relation AS r 
    ON r.item_id = i.id
    WHERE r.tag_id IN (:tags)
    GROUP BY i.id
    ORDER BY id DESC
    LIMIT 10
  `;

var replacements = { tags: currentTags };
var res = await db.query(sql, { type: db.QueryTypes.SELECT, raw: true, replacements });

sql = `
    SELECT COUNT(id) AS count FROM(
        SELECT id FROM tb_item AS i
        LEFT JOIN tb_item_tag_relation AS r 
        ON r.item_id = i.id
        WHERE r.tag_id IN (:tags)
        GROUP BY i.id
    ) t
  `;
res = await db.query(sql, { type: db.QueryTypes.SELECT, raw: true, replacements });


声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
随机推荐
HTML input datetime 日期时间选择器
WordPress 文章页作者信息 get_the_author() 和 get_the_author_meta()
JavaScript class 的 this 指向
JavaScript getter和setter
表驱动方法
WordPress 用户元信息 get_user_meta() 和 update_user_meta()
JavaScript Date 类型
Light 主题