通过指定 sql<number>,你是在告诉 Drizzle 该字段的预期类型是 number。
如果你指定错误(例如,对一个实际会返回 number 的字段使用 sql<string>),运行时的值将不会与预期类型匹配。
Drizzle 无法基于提供的类型泛型执行任何类型转换,因为这些信息在运行时不可用。
如果你需要对返回值应用运行时转换,可以使用 .mapWith() 方法。
要统计表中的所有行数,你可以像下面这样使用 count() 函数或 sql 运算符:
import { count, sql } from 'drizzle-orm';
import { products } from './schema';
const db = drizzle(...);
await db.select({ count: count() }).from(products);
// 在底层,count() 函数会在运行时将其结果转换为 number。
await db.select({ count: sql`count(*)`.mapWith(Number) }).from(products);// 结果类型
type Result = {
count: number;
}[];select count(*) from products;要统计指定列包含非 NULL 值的行数,你可以在 count() 函数中传入一列:
await db.select({ count: count(products.discount) }).from(products);// 结果类型
type Result = {
count: number;
}[];select count(`discount`) from products;Drizzle 提供了简单而灵活的 API,让你可以创建自己的自定义解决方案。在 SingleStore 中,驱动程序可能会将 count() 返回为字符串,因此当你需要数值结果时,请将其转换为 number:
import { AnyColumn, sql } from 'drizzle-orm';
const customCount = (column?: AnyColumn) => {
if (column) {
return sql<number>`cast(count(${column}) as unsigned)`; // 在 SingleStore 中转换为 unsigned integer
} else {
return sql<number>`cast(count(*) as unsigned)`; // 在 SingleStore 中转换为 unsigned integer
}
};
await db.select({ count: customCount() }).from(products);
await db.select({ count: customCount(products.discount) }).from(products);select cast(count(*) as unsigned) from products;
select cast(count(`discount`) as unsigned) from products;通过指定 sql<number>,你是在告诉 Drizzle 该字段的预期类型是 number。
如果你指定错误(例如,对一个实际会返回 number 的字段使用 sql<string>),运行时的值将不会与预期类型匹配。
Drizzle 无法基于提供的类型泛型执行任何类型转换,因为这些信息在运行时不可用。
如果你需要对返回值应用运行时转换,可以使用 .mapWith() 方法。
要统计匹配某个条件的行数,你可以使用 .where() 方法:
import { count, gt } from 'drizzle-orm';
await db
.select({ count: count() })
.from(products)
.where(gt(products.price, 100));select count(*) from products where price > 100下面是如何将 count() 函数与 joins 和 aggregations 结合使用:
import { count, eq } from 'drizzle-orm';
import { countries, cities } from './schema';
// 统计每个国家的城市数量
await db
.select({
country: countries.name,
citiesCount: count(cities.id),
})
.from(countries)
.leftJoin(cities, eq(countries.id, cities.countryId))
.groupBy(countries.id)
.orderBy(countries.name);select countries.name, count(`cities`.`id`) from countries
left join cities on countries.id = cities.country_id
group by countries.id
order by countries.name;