Mysql: COUNT(*) null 存为 1 的问题 -- Typeorm

1,515 阅读1分钟

sql 语句

SELECT
*,
COUNT(DISTINCT article_id) AS count
FROM
tag AS t
LEFT JOIN article_tags AS aat ON t.id = aat.tag_id
GROUP BY
t.id

使用 DISTINCT 字段就行

typeorm 语句

const repository = getManager().getRepository(Tag);
    
const tags = await repository
.createQueryBuilder("tag")
.select(["id", "created_by", "name"])
.addSelect("COUNT(DISTINCT article_id)", "count") // DISTINCT 解決mysql查询null显示1的问题
.leftJoin('article_tags', "aat", "tag.id = aat.tag_id")
.where("status = :status", {status: 0})
.groupBy("tag.id")
.printSql()
.getRawMany()