# 使用 Query Builder 插入

> 英文标题：Insert using Query Builder
> 官网原文：https://typeorm.io/docs/query-builder/insert-query-builder
> 文档版本：TypeORM v1.1
> 体例：英文原文（EN）与中文译文（ZH）逐块并列，共 32 块

---

<!-- EN -->
# Insert using Query Builder

<!-- ZH -->
# 使用 Query Builder 插入

<!-- EN -->
You can create `INSERT` queries using `QueryBuilder`. Examples:

<!-- ZH -->
你可以用 `QueryBuilder` 创建 `INSERT` 查询。示例：

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values([
        { firstName: "Timber", lastName: "Saw" },
        { firstName: "Phantom", lastName: "Lancer" },
    ])
    .execute()
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values([
        { firstName: "Timber", lastName: "Saw" },
        { firstName: "Phantom", lastName: "Lancer" },
    ])
    .execute()
```

<!-- EN -->
This is the most efficient way in terms of performance to insert rows into your database. You can also perform bulk insertions this way.

<!-- ZH -->
从性能角度看，这是向数据库插入行最高效的方式。你也可以用这种方式执行批量插入。

<!-- EN -->
## Raw SQL support

<!-- ZH -->
## 原生 SQL 支持

<!-- EN -->
In some cases when you need to execute SQL queries you need to use function style value:

<!-- ZH -->
在某些需要执行 SQL 查询的场景下，你需要使用函数形式的值：

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: () => "CONCAT('S', 'A', 'W')",
    })
    .execute()
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: () => "CONCAT('S', 'A', 'W')",
    })
    .execute()
```

<!-- EN -->
> Warning: When using raw SQL, ensure that values are properly sanitized to prevent SQL injection.

<!-- ZH -->
> 警告：使用原生 SQL 时，请确保值已被正确转义，以防止 SQL 注入。

<!-- EN -->
## Update values ON CONFLICT

<!-- ZH -->
## 冲突时更新值（ON CONFLICT）

<!-- EN -->
If the values you are trying to insert conflict due to existing data the `orUpdate` function can be used to update specific values on the conflicted target.

<!-- ZH -->
如果你要插入的值因已有数据而发生冲突，可以使用 `orUpdate` 函数来更新冲突目标上的特定值。

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: "Saw",
        externalId: "abc123",
    })
    .orUpdate(["firstName", "lastName"], ["externalId"])
    .execute()
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: "Saw",
        externalId: "abc123",
    })
    .orUpdate(["firstName", "lastName"], ["externalId"])
    .execute()
```

<!-- EN -->
## Update values ON CONFLICT with condition (Postgres, Oracle, MSSQL, SAP HANA)

<!-- ZH -->
## 带条件的冲突时更新（Postgres、Oracle、MSSQL、SAP HANA）

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: "Saw",
        externalId: "abc123",
    })
    .orUpdate(["firstName", "lastName"], ["externalId"], {
        overwriteCondition: {
            where: {
                firstName: Equal("Phantom"),
            },
        },
    })
    .execute()
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: "Saw",
        externalId: "abc123",
    })
    .orUpdate(["firstName", "lastName"], ["externalId"], {
        overwriteCondition: {
            where: {
                firstName: Equal("Phantom"),
            },
        },
    })
    .execute()
```

<!-- EN -->
## IGNORE error (MySQL) or DO NOTHING (Postgres, Oracle, MSSQL, SAP HANA) during insert

<!-- ZH -->
## 插入时忽略错误（MySQL）或什么都不做（Postgres、Oracle、MSSQL、SAP HANA）

<!-- EN -->
If the values you are trying to insert conflict due to existing data or containing invalid data, the `orIgnore` function can be used to suppress errors and insert only rows that contain valid data.

<!-- ZH -->
如果你要插入的值因已有数据而冲突，或者包含非法数据，可以使用 `orIgnore` 函数来抑制错误，只插入包含有效数据的行。

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: "Saw",
        externalId: "abc123",
    })
    .orIgnore()
    .execute()
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: "Saw",
        externalId: "abc123",
    })
    .orIgnore()
    .execute()
```

<!-- EN -->
## Skip data update if values have not changed (Postgres, Oracle, MSSQL, SAP HANA)

<!-- ZH -->
## 值未变化时跳过数据更新（Postgres、Oracle、MSSQL、SAP HANA）

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: "Saw",
        externalId: "abc123",
    })
    .orUpdate(["firstName", "lastName"], ["externalId"], {
        skipUpdateIfNoValuesChanged: true,
    })
    .execute()
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: "Saw",
        externalId: "abc123",
    })
    .orUpdate(["firstName", "lastName"], ["externalId"], {
        skipUpdateIfNoValuesChanged: true,
    })
    .execute()
```

<!-- EN -->
## Use partial index (Postgres)

<!-- ZH -->
## 使用部分索引（Postgres）

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: "Saw",
        externalId: "abc123",
    })
    .orUpdate(["firstName", "lastName"], ["externalId"], {
        skipUpdateIfNoValuesChanged: true,
        indexPredicate: "date > 2020-01-01",
    })
    .execute()
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(User)
    .values({
        firstName: "Timber",
        lastName: "Saw",
        externalId: "abc123",
    })
    .orUpdate(["firstName", "lastName"], ["externalId"], {
        skipUpdateIfNoValuesChanged: true,
        indexPredicate: "date > 2020-01-01",
    })
    .execute()
```

<!-- EN -->
## Insert from Select

<!-- ZH -->
## 从 Select 插入

<!-- EN -->
You can insert data from one table into another using a `SELECT` query with the `valuesFromSelect()` method. This creates an `INSERT INTO ... SELECT FROM` statement, which is useful for data migration, archiving, or copying data between tables.

<!-- ZH -->
你可以用 `valuesFromSelect()` 方法通过 `SELECT` 查询把数据从一张表插入另一张表。这会创建一条 `INSERT INTO ... SELECT FROM` 语句，对数据迁移、归档或在表之间复制数据很有用。

<!-- EN -->
### Using a SelectQueryBuilder directly

<!-- ZH -->
### 直接使用 SelectQueryBuilder

<!-- EN -->
```typescript
// Create a select query to get the source data
const selectQuery = dataSource
    .createQueryBuilder()
    .select(["user.firstName", "user.lastName"])
    .from(User, "user")
    .where("user.isActive = :isActive", { isActive: true })

// Insert the selected data into another table
await dataSource
    .createQueryBuilder()
    .insert()
    .into(ArchivedUser, ["firstName", "lastName"])
    .valuesFromSelect(selectQuery)
    .execute()
```

<!-- ZH -->
```typescript
// 创建一个 select 查询来获取源数据
const selectQuery = dataSource
    .createQueryBuilder()
    .select(["user.firstName", "user.lastName"])
    .from(User, "user")
    .where("user.isActive = :isActive", { isActive: true })

// 把选中的数据插入另一张表
await dataSource
    .createQueryBuilder()
    .insert()
    .into(ArchivedUser, ["firstName", "lastName"])
    .valuesFromSelect(selectQuery)
    .execute()
```

<!-- EN -->
### Using a callback function

<!-- ZH -->
### 使用回调函数

<!-- EN -->
You can also use a callback function to build the select query:

<!-- ZH -->
你也可以用回调函数来构建 select 查询：

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(ArchivedUser, ["firstName", "lastName", "archivedAt"])
    .valuesFromSelect((qb) =>
        qb
            .select(["user.firstName", "user.lastName", "NOW()"])
            .from(User, "user")
            .where("user.deletedAt IS NOT NULL"),
    )
    .execute()
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(ArchivedUser, ["firstName", "lastName", "archivedAt"])
    .valuesFromSelect((qb) =>
        qb
            .select(["user.firstName", "user.lastName", "NOW()"])
            .from(User, "user")
            .where("user.deletedAt IS NOT NULL"),
    )
    .execute()
```

<!-- EN -->
### With joins

<!-- ZH -->
### 带连接

<!-- EN -->
You can use joins in the select query to combine data from multiple tables:

<!-- ZH -->
你可以在 select 查询中使用连接，把多张表的数据组合起来：

<!-- EN -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(UserReport, ["userName", "orderCount"])
    .valuesFromSelect((qb) =>
        qb
            .select(["user.name", "COUNT(order.id)"])
            .from(User, "user")
            .leftJoin("user.orders", "order")
            .groupBy("user.id"),
    )
    .execute()
```

<!-- ZH -->
```typescript
await dataSource
    .createQueryBuilder()
    .insert()
    .into(UserReport, ["userName", "orderCount"])
    .valuesFromSelect((qb) =>
        qb
            .select(["user.name", "COUNT(order.id)"])
            .from(User, "user")
            .leftJoin("user.orders", "order")
            .groupBy("user.id"),
    )
    .execute()
```

<!-- EN -->
> **Note:** When using `valuesFromSelect()`, entity listeners and subscribers (`@BeforeInsert`, `@AfterInsert`) are not called because no entity instances are created during the insert operation.

<!-- ZH -->
> **注意：** 使用 `valuesFromSelect()` 时，实体监听器和订阅者（`@BeforeInsert`、`@AfterInsert`）不会被调用，因为插入过程中不会创建任何实体实例。

<!-- EN -->
> **Note:** The `updateEntity` option has no effect with `valuesFromSelect()` since there are no entity instances to update.

<!-- ZH -->
> **注意：** `updateEntity` 选项对 `valuesFromSelect()` 无效，因为没有可更新的实体实例。
