select count(*) from products;select count("discount") from products;
IMPORTANT
sql<number>를 지정하면 Drizzle에게 해당 필드의 예상 타입이 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() 함수를 사용하는 방법은 다음과 같습니다.
index.ts
schema.ts
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;