TypeORM:选择 DISTINCT 值
在现实生活中,一列可能包含许多重复值。但是,有时您可能只想获得不同(唯一)的值。如果您使用过 MySQL 或 PostgreSQL,您很可能熟悉SELECT DISTINCT语句。你怎么能用TypeORM做到这一点?下面的例子会让事情变得清楚。
这个例子
假设我们有一个名为products的表,其中包含有关商品名称、价格和颜色的信息。我们的目标是列出所有不同的价格和颜色。这是如何做到的:
const productRepository = myDataSource.getRepository(Product);
// select unique prices
const uniquePrices = await productRepository
.createQueryBuilder('product')
.select('DISTINCT product.price', 'price')
.getRawMany();
console.log(uniquePrices);
// select unique colors
const uniqueColors = await productRepository
.createQueryBuilder('product')
.select('product.color', 'color')
.distinct(true)
.getRawMany();
console.log(uniqueColors);
您可能会注意到两个查询构建器之间的细微差别。第一个在选择部分添加DISTINCT,而第二个添加distinct(true) 。
这是您偏好的产品实体:
// Product entity
import {
Entity,
PrimaryGeneratedColumn,
Column,
} from 'typeorm';
@Entity({name: 'products'})
export class Product {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
color: string;
@Column({default: 0})
price: number
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。