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


声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
随机推荐
Express 使用 cors 模块支持跨域
Express 使用 method-override 处理动词覆盖
Node.js 使用 Jest 做单元测试
Nginx 通过日志统计访问数据
MySQL 使用 DATE_FORMAT() 和 FROM_UNIXTIME() 格式化时间
ReferenceError: __dirname is not defined in ES module scope
github Support for password authentication was removed
Node.js url 模块