[英]TypeORM Inner Join Same Table
我有一個問題,我在網上找不到答案。
我有一個表,我希望刪除重復的條目:
我的原始 SQL 查詢是:
#Perform delete duplicate logs with same order_id and message
DELETE t1 FROM order_logs t1
INNER JOIN order_logs t2
WHERE t1.log_id < t2.log_id
AND t1.order_id = t2.order_id
AND t1.message = t2.message
AND t1.order_id = @ORDER_ID
AND t2.order_id = @ORDER_ID;
這是我的@Entity:
@Entity('customer_logs')
export class CustomerLog {
@PrimaryGeneratedColumn()
readonly log_id: number
@Column()
@ManyToOne(() => Customer, (customer) => customer.id, {
onDelete: 'CASCADE',
})
@JoinColumn({ name: 'customer_id' })
readonly customer_id: number
@Column({ default: null, nullable: true })
@ManyToOne(() => User, (user) => user.user_id)
@JoinColumn({ name: 'user_id' })
readonly user_id?: number
@Column()
@IsString()
@MinLength(1)
@MaxLength(255)
readonly message: string
@Column()
@IsEnum(CustomerLogType)
readonly type: CustomerLogType
@Column({ type: 'json', default: null, nullable: true })
@IsObject()
readonly json?: object
@CreateDateColumn()
@Expose({ groups: ['ADMIN', 'OWNER'] })
readonly created_at: Date
@UpdateDateColumn()
@Expose({ groups: ['ADMIN', 'OWNER'] })
readonly updated_at: Date
constructor(partial: Partial<CustomerLog>) {
Object.assign(this, partial)
}
}
您知道我將如何通過 QueryBuilder 使用 TypeORM 執行此查詢嗎?
如果您已經擁有原始 SQL 查詢權限,您可以在代碼中使用它,而無需使用 QueryBuilder 構建它。
import { getConnection } from "typeorm";
.......{
await getConnection().query("DELETE t1 FROM order_logs t1
INNER JOIN order_logs t2
WHERE t1.log_id < t2.log_id
AND t1.order_id = t2.order_id
AND t1.message = t2.message
AND t1.order_id = @ORDER_ID
AND t2.order_id = @ORDER_ID;"
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.