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 });


真诚赞赏,手留余香
赞赏
随机推荐
Node.js 的图片处理模块 images 跨平台图像编解码库
X-sendfile 大文件下载解决方案
CSS 实现三角形
ffmpeg 推送流到nginx服务器,生成m3u8 地址
重构:互联网公司的政治斗争和大清洗
发送header文件头信息实现文件下载
设计的四个基本原则
Cordova build 报错
升级macOS mojove后,sequel pro退出异常,使用Xcode重新编译sequel
apiDoc 参考