# 使用 Query Builder 查询

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

---

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

<!-- ZH -->
# 使用 Query Builder 查询

<!-- EN -->
## What is a QueryBuilder?

<!-- ZH -->
## 什么是 QueryBuilder？

<!-- EN -->
`QueryBuilder` is one of the most powerful features of TypeORM - it allows you to build SQL queries using elegant and convenient syntax, execute them and get automatically transformed entities.

<!-- ZH -->
`QueryBuilder` 是 TypeORM 最强大的特性之一——它让你能用优雅而便捷的语法构建 SQL 查询、执行它们，并拿到自动转换好的实体。

<!-- EN -->
Simple example of `QueryBuilder`:

<!-- ZH -->
`QueryBuilder` 的简单示例：

<!-- EN -->
```typescript
const firstUser = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getOne()
```

<!-- ZH -->
```typescript
const firstUser = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getOne()
```

<!-- EN -->
It builds the following SQL query:

<!-- ZH -->
它会构建如下 SQL 查询：

<!-- EN -->
```sql
SELECT
    user.id as userId,
    user.firstName as userFirstName,
    user.lastName as userLastName
FROM users user
WHERE user.id = 1
```

<!-- ZH -->
```sql
SELECT
    user.id as userId,
    user.firstName as userFirstName,
    user.lastName as userLastName
FROM users user
WHERE user.id = 1
```

<!-- EN -->
and returns you an instance of `User`:

<!-- ZH -->
并返回一个 `User` 实例：

<!-- EN -->
```javascript
User {
    id: 1,
    firstName: "Timber",
    lastName: "Saw"
}
```

<!-- ZH -->
```javascript
User {
    id: 1,
    firstName: "Timber",
    lastName: "Saw"
}
```

<!-- EN -->
## Important note when using the `QueryBuilder`

<!-- ZH -->
## 使用 `QueryBuilder` 时的重要注意事项

<!-- EN -->
When using the `QueryBuilder`, you need to provide unique parameters in your `WHERE` expressions. **This will not work**:

<!-- ZH -->
使用 `QueryBuilder` 时，你需要在 `WHERE` 表达式中提供各不相同的参数名。**下面这样是不行的**：

<!-- EN -->
```typescript
const result = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.linkedSheep", "linkedSheep")
    .leftJoinAndSelect("user.linkedCow", "linkedCow")
    .where("user.linkedSheep = :id", { id: sheepId })
    .andWhere("user.linkedCow = :id", { id: cowId })
```

<!-- ZH -->
```typescript
const result = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.linkedSheep", "linkedSheep")
    .leftJoinAndSelect("user.linkedCow", "linkedCow")
    .where("user.linkedSheep = :id", { id: sheepId })
    .andWhere("user.linkedCow = :id", { id: cowId })
```

<!-- EN -->
... but this will:

<!-- ZH -->
……但这样可以：

<!-- EN -->
```typescript
const result = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.linkedSheep", "linkedSheep")
    .leftJoinAndSelect("user.linkedCow", "linkedCow")
    .where("user.linkedSheep = :sheepId", { sheepId })
    .andWhere("user.linkedCow = :cowId", { cowId })
```

<!-- ZH -->
```typescript
const result = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.linkedSheep", "linkedSheep")
    .leftJoinAndSelect("user.linkedCow", "linkedCow")
    .where("user.linkedSheep = :sheepId", { sheepId })
    .andWhere("user.linkedCow = :cowId", { cowId })
```

<!-- EN -->
Note that we uniquely named `:sheepId` and `:cowId` instead of using `:id` twice for different parameters.

<!-- ZH -->
注意，我们给 `:sheepId` 和 `:cowId` 取了不同的名字，而不是对不同参数两次使用 `:id`。

<!-- EN -->
## How to create and use a QueryBuilder?

<!-- ZH -->
## 如何创建并使用 QueryBuilder？

<!-- EN -->
There are several ways how you can create a `Query Builder`:

<!-- ZH -->
创建 `Query Builder` 有几种方式：

<!-- EN -->
* Using DataSource:

<!-- ZH -->
* 使用 DataSource：

<!-- EN -->
  ```typescript
const user = await dataSource
    .createQueryBuilder()
    .select("user")
    .from(User, "user")
    .where("user.id = :id", { id: 1 })
    .getOne()
  ```

<!-- ZH -->
  ```typescript
const user = await dataSource
    .createQueryBuilder()
    .select("user")
    .from(User, "user")
    .where("user.id = :id", { id: 1 })
    .getOne()
  ```

<!-- EN -->
* Using entity manager:

<!-- ZH -->
* 使用 entity manager：

<!-- EN -->
  ```typescript
const user = await dataSource.manager
    .createQueryBuilder(User, "user")
    .where("user.id = :id", { id: 1 })
    .getOne()
  ```

<!-- ZH -->
  ```typescript
const user = await dataSource.manager
    .createQueryBuilder(User, "user")
    .where("user.id = :id", { id: 1 })
    .getOne()
  ```

<!-- EN -->
* Using repository:

<!-- ZH -->
* 使用 repository：

<!-- EN -->
  ```typescript
const user = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getOne()
  ```

<!-- ZH -->
  ```typescript
const user = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getOne()
  ```

<!-- EN -->
There are 5 different `QueryBuilder` types available:

<!-- ZH -->
共有 5 种不同的 `QueryBuilder` 类型可用：

<!-- EN -->
* `SelectQueryBuilder` - used to build and execute `SELECT` queries. Example:

<!-- ZH -->
* `SelectQueryBuilder` - 用于构建并执行 `SELECT` 查询。示例：

<!-- EN -->
  ```typescript
const user = await dataSource
    .createQueryBuilder()
    .select("user")
    .from(User, "user")
    .where("user.id = :id", { id: 1 })
    .getOne()
  ```

<!-- ZH -->
  ```typescript
const user = await dataSource
    .createQueryBuilder()
    .select("user")
    .from(User, "user")
    .where("user.id = :id", { id: 1 })
    .getOne()
  ```

<!-- EN -->
* `InsertQueryBuilder` - used to build and execute `INSERT` queries. Example:

<!-- ZH -->
* `InsertQueryBuilder` - 用于构建并执行 `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 -->
* `UpdateQueryBuilder` - used to build and execute `UPDATE` queries. Example:

<!-- ZH -->
* `UpdateQueryBuilder` - 用于构建并执行 `UPDATE` 查询。示例：

<!-- EN -->
  ```typescript
await dataSource
    .createQueryBuilder()
    .update(User)
    .set({ firstName: "Timber", lastName: "Saw" })
    .where("id = :id", { id: 1 })
    .execute()
  ```

<!-- ZH -->
  ```typescript
await dataSource
    .createQueryBuilder()
    .update(User)
    .set({ firstName: "Timber", lastName: "Saw" })
    .where("id = :id", { id: 1 })
    .execute()
  ```

<!-- EN -->
* `DeleteQueryBuilder` - used to build and execute `DELETE` queries. Example:

<!-- ZH -->
* `DeleteQueryBuilder` - 用于构建并执行 `DELETE` 查询。示例：

<!-- EN -->
  ```typescript
await dataSource
    .createQueryBuilder()
    .delete()
    .from(User)
    .where("id = :id", { id: 1 })
    .execute()
  ```

<!-- ZH -->
  ```typescript
await dataSource
    .createQueryBuilder()
    .delete()
    .from(User)
    .where("id = :id", { id: 1 })
    .execute()
  ```

<!-- EN -->
* `RelationQueryBuilder` - used to build and execute relation-specific operations \[TBD]. Example:

<!-- ZH -->
* `RelationQueryBuilder` - 用于构建并执行关系专属操作 \[TBD]。示例：

<!-- EN -->
  ```typescript
await dataSource
    .createQueryBuilder()
    .relation(User, "photos")
    .of(id)
    .loadMany()
  ```

<!-- ZH -->
  ```typescript
await dataSource
    .createQueryBuilder()
    .relation(User, "photos")
    .of(id)
    .loadMany()
  ```

<!-- EN -->
You can switch between different types of query builder within any of them, once you do, you will get a new instance of query builder (unlike all other methods).

<!-- ZH -->
你可以在任意一种 query builder 中切换到其他类型，一旦切换就会得到一个新的 query builder 实例（与其他所有方法不同）。

<!-- EN -->
## Getting values using `QueryBuilder`

<!-- ZH -->
## 用 `QueryBuilder` 获取值

<!-- EN -->
To get a single result from the database, for example to get a user by id or name, you must use `getOne`:

<!-- ZH -->
要从数据库获取单条结果，例如按 id 或名字获取一个用户，你必须使用 `getOne`：

<!-- EN -->
```typescript
const timber = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" })
    .getOne()
```

<!-- ZH -->
```typescript
const timber = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" })
    .getOne()
```

<!-- EN -->
`getOneOrFail` will get a single result from the database, but if no result exists it will throw an `EntityNotFoundError`:

<!-- ZH -->
`getOneOrFail` 也会从数据库获取单条结果，但如果不存在任何结果，它会抛出 `EntityNotFoundError`：

<!-- EN -->
```typescript
const timber = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" })
    .getOneOrFail()
```

<!-- ZH -->
```typescript
const timber = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id OR user.name = :name", { id: 1, name: "Timber" })
    .getOneOrFail()
```

<!-- EN -->
To get multiple results from the database, for example, to get all users from the database, use `getMany`:

<!-- ZH -->
要从数据库获取多条结果，例如获取数据库中的所有用户，请使用 `getMany`：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .getMany()
```

<!-- EN -->
There are two types of results you can get using select query builder: **entities** or **raw results**. Most of the time, you need to select real entities from your database, for example, users. For this purpose, you use `getOne` and `getMany`. But sometimes you need to select some specific data, let's say the *sum of all user photos*. This data is not an entity, it's called raw data. To get raw data, you use `getRawOne` and `getRawMany`. Examples:

<!-- ZH -->
使用 select query builder 你可以得到两类结果：**实体 **或** 原生结果**。大多数时候，你需要从数据库中选取真正的实体，例如用户。为此你使用 `getOne` 和 `getMany`。但有时你需要选取某些特定数据，比如*所有用户照片的总和*。这类数据不是实体，它被称为原生数据。要获取原生数据，你使用 `getRawOne` 和 `getRawMany`。示例：

<!-- EN -->
```typescript
const { sum } = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("SUM(user.photosCount)", "sum")
    .where("user.id = :id", { id: 1 })
    .getRawOne()
```

<!-- ZH -->
```typescript
const { sum } = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("SUM(user.photosCount)", "sum")
    .where("user.id = :id", { id: 1 })
    .getRawOne()
```

<!-- EN -->
```typescript
const photosSums = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("user.id")
    .addSelect("SUM(user.photosCount)", "sum")
    .groupBy("user.id")
    .getRawMany()

// result will be like this: [{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]
```

<!-- ZH -->
```typescript
const photosSums = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("user.id")
    .addSelect("SUM(user.photosCount)", "sum")
    .groupBy("user.id")
    .getRawMany()

// 结果会像这样：[{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]
```

<!-- EN -->
## Getting a count

<!-- ZH -->
## 获取数量

<!-- EN -->
You can get the count on the number of rows a query will return by using `getCount()`. This will return the count as a number rather than an Entity result.

<!-- ZH -->
你可以用 `getCount()` 获取一条查询将返回的行数。它返回的是数字而不是实体结果。

<!-- EN -->
```typescript
const count = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.name = :name", { name: "Timber" })
    .getCount()
```

<!-- ZH -->
```typescript
const count = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.name = :name", { name: "Timber" })
    .getCount()
```

<!-- EN -->
Which produces the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT count(*) FROM users user WHERE user.name = 'Timber'
```

<!-- ZH -->
```sql
SELECT count(*) FROM users user WHERE user.name = 'Timber'
```

<!-- EN -->
## What are aliases for?

<!-- ZH -->
## 别名是做什么用的？

<!-- EN -->
We used `createQueryBuilder("user")`. But what is "user"? It's just a regular SQL alias. We use aliases everywhere, except when we work with selected data.

<!-- ZH -->
我们用了 `createQueryBuilder("user")`。但 "user" 是什么？它就是一个普通的 SQL 别名。除了处理被选中的数据之外，我们到处都在使用别名。

<!-- EN -->
`createQueryBuilder("user")` is equivalent to:

<!-- ZH -->
`createQueryBuilder("user")` 等价于：

<!-- EN -->
```typescript
createQueryBuilder().select("user").from(User, "user")
```

<!-- ZH -->
```typescript
createQueryBuilder().select("user").from(User, "user")
```

<!-- EN -->
Which will result in the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user
```

<!-- ZH -->
```sql
SELECT ... FROM users user
```

<!-- EN -->
In this SQL query, `users` is the table name, and `user` is an alias we assign to this table. Later we use this alias to access the table:

<!-- ZH -->
在这条 SQL 查询中，`users` 是表名，`user` 是我们给这张表起的别名。之后我们用这个别名来访问这张表：

<!-- EN -->
```typescript
createQueryBuilder()
    .select("user")
    .from(User, "user")
    .where("user.name = :name", { name: "Timber" })
```

<!-- ZH -->
```typescript
createQueryBuilder()
    .select("user")
    .from(User, "user")
    .where("user.name = :name", { name: "Timber" })
```

<!-- EN -->
Which produces the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user WHERE user.name = 'Timber'
```

<!-- ZH -->
```sql
SELECT ... FROM users user WHERE user.name = 'Timber'
```

<!-- EN -->
See, we used the users table by using the `user` alias we assigned when we created a query builder.

<!-- ZH -->
看，我们通过创建 query builder 时指定的 `user` 别名用到了 users 表。

<!-- EN -->
One query builder is not limited to one alias, they can have multiple aliases. Each select can have its own alias, you can select from multiple tables each with its own alias, you can join multiple tables each with its own alias. You can use those aliases to access tables you are selecting (or data you are selecting).

<!-- ZH -->
一个 query builder 并不局限于一个别名，它可以拥有多个别名。每个 select 都可以有自己的别名，你可以从多张表中选取、每张表各有别名，也可以连接多张表、每张表各有别名。你可以用这些别名访问正在选取的表（或正在选取的数据）。

<!-- EN -->
## Using parameters to escape data

<!-- ZH -->
## 用参数转义数据

<!-- EN -->
We used `where("user.name = :name", { name: "Timber" })`. What does `{ name: "Timber" }` stand for? It's a parameter we used to prevent SQL injection. We could have written: `where("user.name = '" + name + "')`, however this is not safe, as it opens the code to SQL injections. The safe way is to use this special syntax: `where("user.name = :name", { name: "Timber" })`, where `:name` is a parameter name and the value is specified in an object: `{ name: "Timber" }`.

<!-- ZH -->
我们用了 `where("user.name = :name", { name: "Timber" })`。`{ name: "Timber" }` 代表什么？它是我们用来防止 SQL 注入的参数。我们本可以写成：`where("user.name = '" + name + "')`，但这不安全，因为它让代码暴露在 SQL 注入风险之下。安全的做法是使用这种特殊语法：`where("user.name = :name", { name: "Timber" })`，其中 `:name` 是参数名，值在一个对象中给出：`{ name: "Timber" }`。

<!-- EN -->
```typescript
.where("user.name = :name", { name: "Timber" })
```

<!-- ZH -->
```typescript
.where("user.name = :name", { name: "Timber" })
```

<!-- EN -->
is a shortcut for:

<!-- ZH -->
是下面写法的简写：

<!-- EN -->
```typescript
.where("user.name = :name")
.setParameter("name", "Timber")
```

<!-- ZH -->
```typescript
.where("user.name = :name")
.setParameter("name", "Timber")
```

<!-- EN -->
Note: do not use the same parameter name for different values across the query builder. Values will be overridden if you set them multiple times.

<!-- ZH -->
注意：不要在整个 query builder 中对不同的值使用相同的参数名。如果你多次设置同一个参数，先前的值会被覆盖。

<!-- EN -->
You can also supply an array of values, and have them transformed into a list of values in the SQL statement, by using the special expansion syntax:

<!-- ZH -->
你也可以提供一个值数组，并用特殊的展开语法把它们转换成 SQL 语句中的值列表：

<!-- EN -->
```typescript
.where("user.name IN (:...names)", { names: [ "Timber", "Crystal", "Lina" ] })
```

<!-- ZH -->
```typescript
.where("user.name IN (:...names)", { names: [ "Timber", "Crystal", "Lina" ] })
```

<!-- EN -->
Which becomes:

<!-- ZH -->
它会变成：

<!-- EN -->
```sql
WHERE user.name IN ('Timber', 'Crystal', 'Lina')
```

<!-- ZH -->
```sql
WHERE user.name IN ('Timber', 'Crystal', 'Lina')
```

<!-- EN -->
## Adding `WHERE` expression

<!-- ZH -->
## 添加 `WHERE` 表达式

<!-- EN -->
Adding a `WHERE` expression is as easy as:

<!-- ZH -->
添加 `WHERE` 表达式非常简单：

<!-- EN -->
```typescript
createQueryBuilder("user").where("user.name = :name", { name: "Timber" })
```

<!-- ZH -->
```typescript
createQueryBuilder("user").where("user.name = :name", { name: "Timber" })
```

<!-- EN -->
Which will produce:

<!-- ZH -->
它会生成：

<!-- EN -->
```sql
SELECT ... FROM users user WHERE user.name = 'Timber'
```

<!-- ZH -->
```sql
SELECT ... FROM users user WHERE user.name = 'Timber'
```

<!-- EN -->
You can add `AND` into an existing `WHERE` expression:

<!-- ZH -->
你可以在已有的 `WHERE` 表达式中加入 `AND`：

<!-- EN -->
```typescript
createQueryBuilder("user")
    .where("user.firstName = :firstName", { firstName: "Timber" })
    .andWhere("user.lastName = :lastName", { lastName: "Saw" })
```

<!-- ZH -->
```typescript
createQueryBuilder("user")
    .where("user.firstName = :firstName", { firstName: "Timber" })
    .andWhere("user.lastName = :lastName", { lastName: "Saw" })
```

<!-- EN -->
Which will produce the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user WHERE user.firstName = 'Timber' AND user.lastName = 'Saw'
```

<!-- ZH -->
```sql
SELECT ... FROM users user WHERE user.firstName = 'Timber' AND user.lastName = 'Saw'
```

<!-- EN -->
You can add `OR` into an existing `WHERE` expression:

<!-- ZH -->
你可以在已有的 `WHERE` 表达式中加入 `OR`：

<!-- EN -->
```typescript
createQueryBuilder("user")
    .where("user.firstName = :firstName", { firstName: "Timber" })
    .orWhere("user.lastName = :lastName", { lastName: "Saw" })
```

<!-- ZH -->
```typescript
createQueryBuilder("user")
    .where("user.firstName = :firstName", { firstName: "Timber" })
    .orWhere("user.lastName = :lastName", { lastName: "Saw" })
```

<!-- EN -->
Which will produce the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user WHERE user.firstName = 'Timber' OR user.lastName = 'Saw'
```

<!-- ZH -->
```sql
SELECT ... FROM users user WHERE user.firstName = 'Timber' OR user.lastName = 'Saw'
```

<!-- EN -->
You can do an `IN` query with the `WHERE` expression:

<!-- ZH -->
你可以用 `WHERE` 表达式做 `IN` 查询：

<!-- EN -->
```typescript
createQueryBuilder("user").where("user.id IN (:...ids)", { ids: [1, 2, 3, 4] })
```

<!-- ZH -->
```typescript
createQueryBuilder("user").where("user.id IN (:...ids)", { ids: [1, 2, 3, 4] })
```

<!-- EN -->
Which will produce the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user WHERE user.id IN (1, 2, 3, 4)
```

<!-- ZH -->
```sql
SELECT ... FROM users user WHERE user.id IN (1, 2, 3, 4)
```

<!-- EN -->
You can add a complex `WHERE` expression into an existing `WHERE` using `Brackets`

<!-- ZH -->
你可以用 `Brackets` 在已有的 `WHERE` 中加入复杂的 `WHERE` 表达式

<!-- EN -->
```typescript
createQueryBuilder("user")
    .where("user.registered = :registered", { registered: true })
    .andWhere(
        new Brackets((qb) => {
            qb.where("user.firstName = :firstName", {
                firstName: "Timber",
            }).orWhere("user.lastName = :lastName", { lastName: "Saw" })
        }),
    )
```

<!-- ZH -->
```typescript
createQueryBuilder("user")
    .where("user.registered = :registered", { registered: true })
    .andWhere(
        new Brackets((qb) => {
            qb.where("user.firstName = :firstName", {
                firstName: "Timber",
            }).orWhere("user.lastName = :lastName", { lastName: "Saw" })
        }),
    )
```

<!-- EN -->
Which will produce the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user WHERE user.registered = true AND (user.firstName = 'Timber' OR user.lastName = 'Saw')
```

<!-- ZH -->
```sql
SELECT ... FROM users user WHERE user.registered = true AND (user.firstName = 'Timber' OR user.lastName = 'Saw')
```

<!-- EN -->
You can add a negated complex `WHERE` expression into an existing `WHERE` using `NotBrackets`

<!-- ZH -->
你可以用 `NotBrackets` 在已有的 `WHERE` 中加入取反的复杂 `WHERE` 表达式

<!-- EN -->
```typescript
createQueryBuilder("user")
    .where("user.registered = :registered", { registered: true })
    .andWhere(
        new NotBrackets((qb) => {
            qb.where("user.firstName = :firstName", {
                firstName: "Timber",
            }).orWhere("user.lastName = :lastName", { lastName: "Saw" })
        }),
    )
```

<!-- ZH -->
```typescript
createQueryBuilder("user")
    .where("user.registered = :registered", { registered: true })
    .andWhere(
        new NotBrackets((qb) => {
            qb.where("user.firstName = :firstName", {
                firstName: "Timber",
            }).orWhere("user.lastName = :lastName", { lastName: "Saw" })
        }),
    )
```

<!-- EN -->
Which will produce the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user WHERE user.registered = true AND NOT((user.firstName = 'Timber' OR user.lastName = 'Saw'))
```

<!-- ZH -->
```sql
SELECT ... FROM users user WHERE user.registered = true AND NOT((user.firstName = 'Timber' OR user.lastName = 'Saw'))
```

<!-- EN -->
You can combine as many `AND` and `OR` expressions as you need. If you use `.where` more than once you'll override all previous `WHERE` expressions.

<!-- ZH -->
你可以按需组合任意多的 `AND` 与 `OR` 表达式。如果你多次使用 `.where`，之前所有的 `WHERE` 表达式都会被覆盖。

<!-- EN -->
Note: be careful with `orWhere` - if you use complex expressions with both `AND` and `OR` expressions, keep in mind that they are stacked without any pretences. Sometimes you'll need to create a where string instead, and avoid using `orWhere`.

<!-- ZH -->
注意：使用 `orWhere` 时要小心——如果你同时用了含 `AND` 与 `OR` 的复杂表达式，请记住它们是毫无修饰地层层堆叠的。有时你需要自己拼一个 where 字符串，并避免使用 `orWhere`。

<!-- EN -->
## Adding `HAVING` expression

<!-- ZH -->
## 添加 `HAVING` 表达式

<!-- EN -->
Adding a `HAVING` expression is easy as:

<!-- ZH -->
添加 `HAVING` 表达式很简单：

<!-- EN -->
```typescript
createQueryBuilder("user").having("user.name = :name", { name: "Timber" })
```

<!-- ZH -->
```typescript
createQueryBuilder("user").having("user.name = :name", { name: "Timber" })
```

<!-- EN -->
Which will produce following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user HAVING user.name = 'Timber'
```

<!-- ZH -->
```sql
SELECT ... FROM users user HAVING user.name = 'Timber'
```

<!-- EN -->
You can add `AND` into an exist `HAVING` expression:

<!-- ZH -->
你可以在已有的 `HAVING` 表达式中加入 `AND`：

<!-- EN -->
```typescript
createQueryBuilder("user")
    .having("user.firstName = :firstName", { firstName: "Timber" })
    .andHaving("user.lastName = :lastName", { lastName: "Saw" })
```

<!-- ZH -->
```typescript
createQueryBuilder("user")
    .having("user.firstName = :firstName", { firstName: "Timber" })
    .andHaving("user.lastName = :lastName", { lastName: "Saw" })
```

<!-- EN -->
Which will produce the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user HAVING user.firstName = 'Timber' AND user.lastName = 'Saw'
```

<!-- ZH -->
```sql
SELECT ... FROM users user HAVING user.firstName = 'Timber' AND user.lastName = 'Saw'
```

<!-- EN -->
You can add `OR` into a exist `HAVING` expression:

<!-- ZH -->
你可以在已有的 `HAVING` 表达式中加入 `OR`：

<!-- EN -->
```typescript
createQueryBuilder("user")
    .having("user.firstName = :firstName", { firstName: "Timber" })
    .orHaving("user.lastName = :lastName", { lastName: "Saw" })
```

<!-- ZH -->
```typescript
createQueryBuilder("user")
    .having("user.firstName = :firstName", { firstName: "Timber" })
    .orHaving("user.lastName = :lastName", { lastName: "Saw" })
```

<!-- EN -->
Which will produce the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user HAVING user.firstName = 'Timber' OR user.lastName = 'Saw'
```

<!-- ZH -->
```sql
SELECT ... FROM users user HAVING user.firstName = 'Timber' OR user.lastName = 'Saw'
```

<!-- EN -->
You can combine as many `AND` and `OR` expressions as you need. If you use `.having` more than once you'll override all previous `HAVING` expressions.

<!-- ZH -->
你可以按需组合任意多的 `AND` 与 `OR` 表达式。如果你多次使用 `.having`，之前所有的 `HAVING` 表达式都会被覆盖。

<!-- EN -->
## Adding `ORDER BY` expression

<!-- ZH -->
## 添加 `ORDER BY` 表达式

<!-- EN -->
Adding an `ORDER BY` expression is easy as:

<!-- ZH -->
添加 `ORDER BY` 表达式很简单：

<!-- EN -->
```typescript
createQueryBuilder("user").orderBy("user.id")
```

<!-- ZH -->
```typescript
createQueryBuilder("user").orderBy("user.id")
```

<!-- EN -->
Which will produce:

<!-- ZH -->
它会生成：

<!-- EN -->
```sql
SELECT ... FROM users user ORDER BY user.id
```

<!-- ZH -->
```sql
SELECT ... FROM users user ORDER BY user.id
```

<!-- EN -->
You can change the ordering direction from ascending to descending (or versa):

<!-- ZH -->
你可以把排序方向从升序改为降序（或反过来）：

<!-- EN -->
```typescript
createQueryBuilder("user").orderBy("user.id", "DESC")

createQueryBuilder("user").orderBy("user.id", "ASC")
```

<!-- ZH -->
```typescript
createQueryBuilder("user").orderBy("user.id", "DESC")

createQueryBuilder("user").orderBy("user.id", "ASC")
```

<!-- EN -->
You can add multiple order-by criteria:

<!-- ZH -->
你可以添加多个排序条件：

<!-- EN -->
```typescript
createQueryBuilder("user").orderBy("user.name").addOrderBy("user.id")
```

<!-- ZH -->
```typescript
createQueryBuilder("user").orderBy("user.name").addOrderBy("user.id")
```

<!-- EN -->
You can also use a map of order-by fields:

<!-- ZH -->
你也可以使用排序字段的映射：

<!-- EN -->
```typescript
createQueryBuilder("user").orderBy({
    "user.name": "ASC",
    "user.id": "DESC",
})
```

<!-- ZH -->
```typescript
createQueryBuilder("user").orderBy({
    "user.name": "ASC",
    "user.id": "DESC",
})
```

<!-- EN -->
If you use `.orderBy` more than once you'll override all previous `ORDER BY` expressions.

<!-- ZH -->
如果你多次使用 `.orderBy`，之前所有的 `ORDER BY` 表达式都会被覆盖。

<!-- EN -->
## Adding `DISTINCT ON` expression (Postgres only)

<!-- ZH -->
## 添加 `DISTINCT ON` 表达式（仅 Postgres）

<!-- EN -->
When using both distinct-on with an order-by expression, the distinct-on expression must match the leftmost order-by. The distinct-on expressions are interpreted using the same rules as order-by. Please note that, using distinct-on without an order-by expression means that the first row of each set is unpredictable.

<!-- ZH -->
当同时使用 distinct-on 与 order-by 表达式时，distinct-on 表达式必须与最左侧的 order-by 相匹配。distinct-on 表达式的解释规则与 order-by 相同。请注意，在没有 order-by 表达式的情况下使用 distinct-on，意味着每个分组中取到哪一行是不可预测的。

<!-- EN -->
Adding a `DISTINCT ON` expression is easy as:

<!-- ZH -->
添加 `DISTINCT ON` 表达式很简单：

<!-- EN -->
```typescript
createQueryBuilder("user").distinctOn(["user.id"]).orderBy("user.id")
```

<!-- ZH -->
```typescript
createQueryBuilder("user").distinctOn(["user.id"]).orderBy("user.id")
```

<!-- EN -->
Which will produce:

<!-- ZH -->
它会生成：

<!-- EN -->
```sql
SELECT DISTINCT ON (user.id) ... FROM users user ORDER BY user.id
```

<!-- ZH -->
```sql
SELECT DISTINCT ON (user.id) ... FROM users user ORDER BY user.id
```

<!-- EN -->
## Adding `GROUP BY` expression

<!-- ZH -->
## 添加 `GROUP BY` 表达式

<!-- EN -->
Adding a `GROUP BY` expression is easy as:

<!-- ZH -->
添加 `GROUP BY` 表达式很简单：

<!-- EN -->
```typescript
createQueryBuilder("user").groupBy("user.id")
```

<!-- ZH -->
```typescript
createQueryBuilder("user").groupBy("user.id")
```

<!-- EN -->
Which will produce the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user GROUP BY user.id
```

<!-- ZH -->
```sql
SELECT ... FROM users user GROUP BY user.id
```

<!-- EN -->
To add more group-by criteria use `addGroupBy`:

<!-- ZH -->
要添加更多分组条件，请使用 `addGroupBy`：

<!-- EN -->
```typescript
createQueryBuilder("user").groupBy("user.name").addGroupBy("user.id")
```

<!-- ZH -->
```typescript
createQueryBuilder("user").groupBy("user.name").addGroupBy("user.id")
```

<!-- EN -->
If you use `.groupBy` more than once you'll override all previous `GROUP BY` expressions.

<!-- ZH -->
如果你多次使用 `.groupBy`，之前所有的 `GROUP BY` 表达式都会被覆盖。

<!-- EN -->
## Adding `LIMIT` expression

<!-- ZH -->
## 添加 `LIMIT` 表达式

<!-- EN -->
Adding a `LIMIT` expression is easy as:

<!-- ZH -->
添加 `LIMIT` 表达式很简单：

<!-- EN -->
```typescript
createQueryBuilder("user").limit(10)
```

<!-- ZH -->
```typescript
createQueryBuilder("user").limit(10)
```

<!-- EN -->
Which will produce the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user LIMIT 10
```

<!-- ZH -->
```sql
SELECT ... FROM users user LIMIT 10
```

<!-- EN -->
The resulting SQL query depends on the type of database (SQL, mySQL, Postgres, etc). Note: LIMIT may not work as you may expect if you are using complex queries with joins or subqueries. If you are using pagination, it's recommended to use `take` instead.

<!-- ZH -->
最终生成的 SQL 查询取决于数据库类型（SQL、mySQL、Postgres 等）。注意：如果你使用的是带连接或子查询的复杂查询，LIMIT 的表现可能与预期不符。如果你做的是分页，建议改用 `take`。

<!-- EN -->
## Adding `OFFSET` expression

<!-- ZH -->
## 添加 `OFFSET` 表达式

<!-- EN -->
Adding an SQL `OFFSET` expression is easy as:

<!-- ZH -->
添加 SQL `OFFSET` 表达式很简单：

<!-- EN -->
```typescript
createQueryBuilder("user").offset(10)
```

<!-- ZH -->
```typescript
createQueryBuilder("user").offset(10)
```

<!-- EN -->
Which will produce the following SQL query:

<!-- ZH -->
它会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT ... FROM users user OFFSET 10
```

<!-- ZH -->
```sql
SELECT ... FROM users user OFFSET 10
```

<!-- EN -->
The resulting SQL query depends on the type of database (SQL, mySQL, Postgres, etc). Note: OFFSET may not work as you may expect if you are using complex queries with joins or subqueries. If you are using pagination, it's recommended to use `skip` instead.

<!-- ZH -->
最终生成的 SQL 查询取决于数据库类型（SQL、mySQL、Postgres 等）。注意：如果你使用的是带连接或子查询的复杂查询，OFFSET 的表现可能与预期不符。如果你做的是分页，建议改用 `skip`。

<!-- EN -->
## Joining relations

<!-- ZH -->
## 连接关系

<!-- EN -->
Let's say you have the following entities:

<!-- ZH -->
假设你有以下实体：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @OneToMany((type) => Photo, (photo) => photo.user)
    photos: Photo[]
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, OneToMany } from "typeorm"
import { Photo } from "./Photo"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @OneToMany((type) => Photo, (photo) => photo.user)
    photos: Photo[]
}
```

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"
import { User } from "./User"

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    url: string

    @ManyToOne((type) => User, (user) => user.photos)
    user: User
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm"
import { User } from "./User"

@Entity()
export class Photo {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    url: string

    @ManyToOne((type) => User, (user) => user.photos)
    user: User
}
```

<!-- EN -->
Now let's say you want to load user "Timber" with all of his photos:

<!-- ZH -->
现在假设你想加载用户 "Timber" 以及他的所有照片：

<!-- EN -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .getOne()
```

<!-- ZH -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .getOne()
```

<!-- EN -->
You'll get the following result:

<!-- ZH -->
你会得到如下结果：

<!-- EN -->
```typescript
{
    id: 1,
    name: "Timber",
    photos: [{
        id: 1,
        url: "me-with-chakram.jpg"
    }, {
        id: 2,
        url: "me-with-trees.jpg"
    }]
}
```

<!-- ZH -->
```typescript
{
    id: 1,
    name: "Timber",
    photos: [{
        id: 1,
        url: "me-with-chakram.jpg"
    }, {
        id: 2,
        url: "me-with-trees.jpg"
    }]
}
```

<!-- EN -->
As you can see `leftJoinAndSelect` automatically loaded all of Timber's photos. The first argument is the relation you want to load and the second argument is an alias you assign to this relation's table. You can use this alias anywhere in query builder. For example, let's take all Timber's photos which aren't removed.

<!-- ZH -->
如你所见，`leftJoinAndSelect` 自动加载了 Timber 的所有照片。第一个参数是你想加载的关系，第二个参数是你给该关系的表起的别名。你可以在 query builder 中的任何地方使用这个别名。例如，我们来取出 Timber 所有未被移除的照片。

<!-- EN -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .andWhere("photo.isRemoved = :isRemoved", { isRemoved: false })
    .getOne()
```

<!-- ZH -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .andWhere("photo.isRemoved = :isRemoved", { isRemoved: false })
    .getOne()
```

<!-- EN -->
This will generate following SQL query:

<!-- ZH -->
这会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT user.*, photo.* FROM users user
    LEFT JOIN photos photo ON photo.user = user.id
    WHERE user.name = 'Timber' AND photo.isRemoved = FALSE
```

<!-- ZH -->
```sql
SELECT user.*, photo.* FROM users user
    LEFT JOIN photos photo ON photo.user = user.id
    WHERE user.name = 'Timber' AND photo.isRemoved = FALSE
```

<!-- EN -->
You can also add conditions to the join expression instead of using "where":

<!-- ZH -->
你也可以把条件加到连接表达式上，而不是用 "where"：

<!-- EN -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo", "photo.isRemoved = :isRemoved", {
        isRemoved: false,
    })
    .where("user.name = :name", { name: "Timber" })
    .getOne()
```

<!-- ZH -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo", "photo.isRemoved = :isRemoved", {
        isRemoved: false,
    })
    .where("user.name = :name", { name: "Timber" })
    .getOne()
```

<!-- EN -->
This will generate the following SQL query:

<!-- ZH -->
这会生成如下 SQL 查询：

<!-- EN -->
```sql
SELECT user.*, photo.* FROM users user
    LEFT JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
    WHERE user.name = 'Timber'
```

<!-- ZH -->
```sql
SELECT user.*, photo.* FROM users user
    LEFT JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
    WHERE user.name = 'Timber'
```

<!-- EN -->
## Inner and left joins

<!-- ZH -->
## 内连接与左连接

<!-- EN -->
If you want to use `INNER JOIN` instead of `LEFT JOIN` just use `innerJoinAndSelect` instead:

<!-- ZH -->
如果你想用 `INNER JOIN` 而不是 `LEFT JOIN`，只需改用 `innerJoinAndSelect`：

<!-- EN -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .innerJoinAndSelect(
        "user.photos",
        "photo",
        "photo.isRemoved = :isRemoved",
        { isRemoved: false },
    )
    .where("user.name = :name", { name: "Timber" })
    .getOne()
```

<!-- ZH -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .innerJoinAndSelect(
        "user.photos",
        "photo",
        "photo.isRemoved = :isRemoved",
        { isRemoved: false },
    )
    .where("user.name = :name", { name: "Timber" })
    .getOne()
```

<!-- EN -->
This will generate:

<!-- ZH -->
这会生成：

<!-- EN -->
```sql
SELECT user.*, photo.* FROM users user
    INNER JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
    WHERE user.name = 'Timber'
```

<!-- ZH -->
```sql
SELECT user.*, photo.* FROM users user
    INNER JOIN photos photo ON photo.user = user.id AND photo.isRemoved = FALSE
    WHERE user.name = 'Timber'
```

<!-- EN -->
The difference between `LEFT JOIN` and `INNER JOIN` is that `INNER JOIN` won't return a user if it does not have any photos. `LEFT JOIN` will return you the user even if it doesn't have photos. To learn more about different join types, refer to the [SQL documentation](https://msdn.microsoft.com/en-us/library/zt8wzxy4.aspx).

<!-- ZH -->
`LEFT JOIN` 与 `INNER JOIN` 的区别在于：如果一个用户没有任何照片，`INNER JOIN` 不会返回该用户；而 `LEFT JOIN` 即使他没有照片也会返回该用户。要进一步了解不同的连接类型，请参阅 [SQL 文档](https://msdn.microsoft.com/en-us/library/zt8wzxy4.aspx)。

<!-- EN -->
## Join without selection

<!-- ZH -->
## 连接但不选取

<!-- EN -->
You can join data without its selection. To do that, use `leftJoin` or `innerJoin`:

<!-- ZH -->
你可以连接数据而不选取它。要做到这一点，请使用 `leftJoin` 或 `innerJoin`：

<!-- EN -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .innerJoin("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .getOne()
```

<!-- ZH -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .innerJoin("user.photos", "photo")
    .where("user.name = :name", { name: "Timber" })
    .getOne()
```

<!-- EN -->
This will generate:

<!-- ZH -->
这会生成：

<!-- EN -->
```sql
SELECT user.* FROM users user
    INNER JOIN photos photo ON photo.user = user.id
    WHERE user.name = 'Timber'
```

<!-- ZH -->
```sql
SELECT user.* FROM users user
    INNER JOIN photos photo ON photo.user = user.id
    WHERE user.name = 'Timber'
```

<!-- EN -->
This will select Timber if he has photos, but won't return his photos.

<!-- ZH -->
这会在 Timber 有照片时选中他，但不会返回他的照片。

<!-- EN -->
## Joining any entity or table

<!-- ZH -->
## 连接任意实体或表

<!-- EN -->
You can join not only relations, but also other unrelated entities or tables. Examples:

<!-- ZH -->
你不仅能连接关系，还能连接其他不相关的实体或表。示例：

<!-- EN -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndSelect(Photo, "photo", "photo.userId = user.id")
    .getMany()
```

<!-- ZH -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndSelect(Photo, "photo", "photo.userId = user.id")
    .getMany()
```

<!-- EN -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndSelect("photos", "photo", "photo.userId = user.id")
    .getMany()
```

<!-- ZH -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndSelect("photos", "photo", "photo.userId = user.id")
    .getMany()
```

<!-- EN -->
## Joining and mapping functionality

<!-- ZH -->
## 连接与映射功能

<!-- EN -->
Add `profilePhoto` to `User` entity, and you can map any data into that property using `QueryBuilder`:

<!-- ZH -->
给 `User` 实体加上 `profilePhoto`，你就可以用 `QueryBuilder` 把任意数据映射到该属性上：

<!-- EN -->
```typescript
export class User {
    /// ...
    profilePhoto: Photo
}
```

<!-- ZH -->
```typescript
export class User {
    /// ...
    profilePhoto: Photo
}
```

<!-- EN -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndMapOne(
        "user.profilePhoto",
        "user.photos",
        "photo",
        "photo.isForProfile = TRUE",
    )
    .where("user.name = :name", { name: "Timber" })
    .getOne()
```

<!-- ZH -->
```typescript
const user = await dataSource
    .createQueryBuilder("user")
    .leftJoinAndMapOne(
        "user.profilePhoto",
        "user.photos",
        "photo",
        "photo.isForProfile = TRUE",
    )
    .where("user.name = :name", { name: "Timber" })
    .getOne()
```

<!-- EN -->
This will load Timber's profile photo and set it to `user.profilePhoto`. If you want to load and map a single entity use `leftJoinAndMapOne`. If you want to load and map multiple entities use `leftJoinAndMapMany`.

<!-- ZH -->
这会加载 Timber 的头像照片并把它设置到 `user.profilePhoto`。如果你想加载并映射单个实体，请使用 `leftJoinAndMapOne`。如果你想加载并映射多个实体，请使用 `leftJoinAndMapMany`。

<!-- EN -->
## Getting the generated query

<!-- ZH -->
## 获取生成的查询

<!-- EN -->
Sometimes you may want to get the SQL query generated by `QueryBuilder`. To do so, use `getSql`:

<!-- ZH -->
有时你可能想拿到 `QueryBuilder` 生成的 SQL 查询。要做到这一点，请使用 `getSql`：

<!-- EN -->
```typescript
const sql = dataSource
    .createQueryBuilder("user")
    .where("user.firstName = :firstName", { firstName: "Timber" })
    .orWhere("user.lastName = :lastName", { lastName: "Saw" })
    .getSql()
```

<!-- ZH -->
```typescript
const sql = dataSource
    .createQueryBuilder("user")
    .where("user.firstName = :firstName", { firstName: "Timber" })
    .orWhere("user.lastName = :lastName", { lastName: "Saw" })
    .getSql()
```

<!-- EN -->
For debugging purposes you can inspect the generated SQL using `getSql()` or `getQuery()`:

<!-- ZH -->
出于调试目的，你可以用 `getSql()` 或 `getQuery()` 查看生成的 SQL：

<!-- EN -->
```typescript
const qb = dataSource
    .createQueryBuilder("user")
    .where("user.firstName = :firstName", { firstName: "Timber" })
    .orWhere("user.lastName = :lastName", { lastName: "Saw" })

console.log(qb.getSql())
// SELECT ... WHERE "user"."firstName" = $1 OR "user"."lastName" = $2

const users = await qb.getMany()
```

<!-- ZH -->
```typescript
const qb = dataSource
    .createQueryBuilder("user")
    .where("user.firstName = :firstName", { firstName: "Timber" })
    .orWhere("user.lastName = :lastName", { lastName: "Saw" })

console.log(qb.getSql())
// SELECT ... WHERE "user"."firstName" = $1 OR "user"."lastName" = $2

const users = await qb.getMany()
```

<!-- EN -->
`getSql()` returns the SQL with parameter placeholders. `getQuery()` returns the same SQL string. To also see the parameter values, use `getQueryAndParameters()` which returns a `[sql, parameters]` tuple.

<!-- ZH -->
`getSql()` 返回带参数占位符的 SQL。`getQuery()` 返回同样的 SQL 字符串。如果还想看到参数值，请使用 `getQueryAndParameters()`，它返回一个 `[sql, parameters]` 元组。

<!-- EN -->
All executed queries are also automatically logged through the configured logger when you enable query logging in your DataSource options:

<!-- ZH -->
当你在 DataSource 选项中启用查询日志时，所有已执行的查询也都会通过所配置的日志记录器自动记录：

<!-- EN -->
```typescript
new DataSource({
    // ...
    logging: ["query"],
})
```

<!-- ZH -->
```typescript
new DataSource({
    // ...
    logging: ["query"],
})
```

<!-- EN -->
## Getting raw results

<!-- ZH -->
## 获取原生结果

<!-- EN -->
There are two types of results you can get using select query builder: **entities** and **raw results**. Most of the time, you need to select real entities from your database, for example, users. For this purpose, you use `getOne` and `getMany`. However, sometimes you need to select specific data, like the *sum of all user photos*. Such data is not an entity, it's called raw data. To get raw data, you use `getRawOne` and `getRawMany`. Examples:

<!-- ZH -->
使用 select query builder 你可以得到两类结果：**实体 **和** 原生结果**。大多数时候，你需要从数据库中选取真正的实体，例如用户。为此你使用 `getOne` 和 `getMany`。不过，有时你需要选取特定数据，比如*所有用户照片的总和*。这类数据不是实体，它被称为原生数据。要获取原生数据，你使用 `getRawOne` 和 `getRawMany`。示例：

<!-- EN -->
```typescript
const { sum } = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("SUM(user.photosCount)", "sum")
    .where("user.id = :id", { id: 1 })
    .getRawOne()
```

<!-- ZH -->
```typescript
const { sum } = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("SUM(user.photosCount)", "sum")
    .where("user.id = :id", { id: 1 })
    .getRawOne()
```

<!-- EN -->
```typescript
const photosSums = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("user.id")
    .addSelect("SUM(user.photosCount)", "sum")
    .groupBy("user.id")
    .getRawMany()

// result will be like this: [{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]
```

<!-- ZH -->
```typescript
const photosSums = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("user.id")
    .addSelect("SUM(user.photosCount)", "sum")
    .groupBy("user.id")
    .getRawMany()

// 结果会像这样：[{ id: 1, sum: 25 }, { id: 2, sum: 13 }, ...]
```

<!-- EN -->
## Streaming result data

<!-- ZH -->
## 流式处理结果数据

<!-- EN -->
You can use `stream` which returns you a stream. Streaming returns you raw data, and you must handle entity transformation manually:

<!-- ZH -->
你可以使用 `stream`，它会返回一个流。流式处理返回的是原生数据，你必须手动处理实体转换：

<!-- EN -->
```typescript
const stream = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .stream()
```

<!-- ZH -->
```typescript
const stream = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .stream()
```

<!-- EN -->
## Using pagination

<!-- ZH -->
## 使用分页

<!-- EN -->
Most of the time when you develop an application, you need pagination functionality. This is used if you have pagination, page slider, or infinite scroll components in your application.

<!-- ZH -->
开发应用时，大多数时候你都需要分页功能。当你的应用中有分页、页面滑块或无限滚动组件时就会用到它。

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .take(10)
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .take(10)
    .getMany()
```

<!-- EN -->
This will give you the first 10 users with their photos.

<!-- ZH -->
这会给你前 10 个用户及其照片。

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .skip(10)
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .skip(10)
    .getMany()
```

<!-- EN -->
This will give you all except the first 10 users with their photos. You can combine those methods:

<!-- ZH -->
这会给你除前 10 个用户之外的所有用户及其照片。你可以组合这两个方法：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .skip(5)
    .take(10)
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .leftJoinAndSelect("user.photos", "photo")
    .skip(5)
    .take(10)
    .getMany()
```

<!-- EN -->
This will skip the first 5 users and take 10 users after them.

<!-- ZH -->
这会跳过前 5 个用户，然后取其后的 10 个用户。

<!-- EN -->
`take` and `skip` may look like we are using `limit` and `offset`, but they aren't. `limit` and `offset` may not work as you expect once you have more complicated queries with joins or subqueries. Using `take` and `skip` will prevent those issues.

<!-- ZH -->
`take` 和 `skip` 看起来像是我们在用 `limit` 和 `offset`，但其实不是。一旦你有更复杂的、带连接或子查询的查询，`limit` 和 `offset` 的表现就可能与预期不符。使用 `take` 和 `skip` 能避免这些问题。

<!-- EN -->
## Set locking

<!-- ZH -->
## 设置锁

<!-- EN -->
QueryBuilder supports both optimistic and pessimistic locking.

<!-- ZH -->
QueryBuilder 同时支持乐观锁和悲观锁。

<!-- EN -->
### Lock modes

<!-- ZH -->
### 锁模式

<!-- EN -->
Support of lock modes, and SQL statements they translate to, are listed in the table below (blank cell denotes unsupported). When specified lock mode is not supported, a `LockNotSupportedOnGivenDriverError` error will be thrown.

<!-- ZH -->
下表列出了各锁模式的支持情况以及它们被转换成的 SQL 语句（空白单元格表示不支持）。当指定的锁模式不被支持时，会抛出 `LockNotSupportedOnGivenDriverError` 错误。

<!-- EN -->
|                       | pessimistic_read                             | pessimistic_write         | dirty_read      | for_no_key_update   | for_key_share   |
| --------------------- | -------------------------------------------- | ------------------------- | --------------- | ------------------- | --------------- |
| MySQL, MariaDB        | `FOR SHARE` (MySQL 8+), `LOCK IN SHARE MODE` | `FOR UPDATE`              | (nothing)       |                     |                 |
| Oracle                | `FOR UPDATE`                                 | `FOR UPDATE`              | (nothing)       |                     |                 |
| Postgres, CockroachDB | `FOR SHARE`                                  | `FOR UPDATE`              | (nothing)       | `FOR NO KEY UPDATE` | `FOR KEY SHARE` |
| SAP HANA              | `FOR SHARE LOCK`                             | `FOR UPDATE`              | (nothing)       |                     |                 |
| SQL Server            | `WITH (HOLDLOCK, ROWLOCK)`                   | `WITH (UPDLOCK, ROWLOCK)` | `WITH (NOLOCK)` |                     |                 |

<!-- ZH -->
|                       | pessimistic_read                             | pessimistic_write         | dirty_read      | for_no_key_update   | for_key_share   |
| --------------------- | -------------------------------------------- | ------------------------- | --------------- | ------------------- | --------------- |
| MySQL, MariaDB        | `FOR SHARE` (MySQL 8+), `LOCK IN SHARE MODE` | `FOR UPDATE`              | (nothing)       |                     |                 |
| Oracle                | `FOR UPDATE`                                 | `FOR UPDATE`              | (nothing)       |                     |                 |
| Postgres, CockroachDB | `FOR SHARE`                                  | `FOR UPDATE`              | (nothing)       | `FOR NO KEY UPDATE` | `FOR KEY SHARE` |
| SAP HANA              | `FOR SHARE LOCK`                             | `FOR UPDATE`              | (nothing)       |                     |                 |
| SQL Server            | `WITH (HOLDLOCK, ROWLOCK)`                   | `WITH (UPDLOCK, ROWLOCK)` | `WITH (NOLOCK)` |                     |                 |

<!-- EN -->
To use pessimistic read locking use the following method:

<!-- ZH -->
要使用悲观读锁，请使用以下方法：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("pessimistic_read")
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("pessimistic_read")
    .getMany()
```

<!-- EN -->
To use pessimistic write locking use the following method:

<!-- ZH -->
要使用悲观写锁，请使用以下方法：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("pessimistic_write")
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("pessimistic_write")
    .getMany()
```

<!-- EN -->
To use dirty read locking use the following method:

<!-- ZH -->
要使用脏读锁，请使用以下方法：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("dirty_read")
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("dirty_read")
    .getMany()
```

<!-- EN -->
To use optimistic locking use the following method:

<!-- ZH -->
要使用乐观锁，请使用以下方法：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("optimistic", existUser.version)
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("optimistic", existUser.version)
    .getMany()
```

<!-- EN -->
Optimistic locking works in conjunction with both `@Version` and `@UpdatedDate` decorators.

<!-- ZH -->
乐观锁与 `@Version` 和 `@UpdatedDate` 装饰器配合使用。

<!-- EN -->
### Lock tables

<!-- ZH -->
### 锁表

<!-- EN -->
You can also lock tables using the following method:

<!-- ZH -->
你也可以用以下方法锁表：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(Post)
    .createQueryBuilder("post")
    .leftJoin("post.author", "user")
    .setLock("pessimistic_write", undefined, ["post"])
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(Post)
    .createQueryBuilder("post")
    .leftJoin("post.author", "user")
    .setLock("pessimistic_write", undefined, ["post"])
    .getMany()
```

<!-- EN -->
If the Lock Tables argument is provided, only the table that is locked in the `FOR UPDATE OF` clause is specified. Lock tables are supported in PostgreSQL / CockroachDB only.

<!-- ZH -->
如果提供了 Lock Tables 参数，那么 `FOR UPDATE OF` 子句中只会指定被锁的那张表。锁表仅在 PostgreSQL / CockroachDB 上受支持。

<!-- EN -->
### setOnLocked

<!-- ZH -->
### setOnLocked

<!-- EN -->
Allows you to control what happens when a row is locked. By default, the database will wait for the lock. You can control that behavior by using `setOnLocked`

<!-- ZH -->
它让你可以控制某行被锁定时会发生什么。默认情况下，数据库会等待锁。你可以用 `setOnLocked` 控制这一行为

<!-- EN -->
To not wait:

<!-- ZH -->
不等待：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("pessimistic_write")
    .setOnLocked("nowait")
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("pessimistic_write")
    .setOnLocked("nowait")
    .getMany()
```

<!-- EN -->
To skip the row:

<!-- ZH -->
跳过该行：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("pessimistic_write")
    .setOnLocked("skip_locked")
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .setLock("pessimistic_write")
    .setOnLocked("skip_locked")
    .getMany()
```

<!-- EN -->
Database support for `setOnLocked` based on [lock mode](#lock-modes):

<!-- ZH -->
各数据库基于[锁模式](#lock-modes)对 `setOnLocked` 的支持情况：

<!-- EN -->
* MySQL < 8, Maria DB: `pessimistic_write`
* MySQL 8+: `pessimistic_read`, `pessimistic_write`
* Oracle: `pessimistic_write`
* Postgres, Cockroach: `pessimistic_read`, `pessimistic_write`, `for_no_key_update`, `for_key_share`
* SAP HANA: `pessimistic_read`, `pessimistic_write`

<!-- ZH -->
* MySQL < 8、Maria DB：`pessimistic_write`
* MySQL 8+：`pessimistic_read`、`pessimistic_write`
* Oracle：`pessimistic_write`
* Postgres、Cockroach：`pessimistic_read`、`pessimistic_write`、`for_no_key_update`、`for_key_share`
* SAP HANA：`pessimistic_read`、`pessimistic_write`

<!-- EN -->
## Use custom index

<!-- ZH -->
## 使用自定义索引

<!-- EN -->
You can provide a certain index for database server to use in some cases. This feature is only supported in MySQL.

<!-- ZH -->
在某些情况下，你可以指定数据库服务器使用某个特定索引。该特性仅在 MySQL 上受支持。

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .useIndex("my_index") // name of index
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .useIndex("my_index") // 索引名
    .getMany()
```

<!-- EN -->
## Max execution time

<!-- ZH -->
## 最大执行时间

<!-- EN -->
We can drop slow query to avoid crashing the server.

<!-- ZH -->
我们可以丢弃慢查询，以避免服务器崩溃。

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .maxExecutionTime(1000) // milliseconds.
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .maxExecutionTime(1000) // 毫秒。
    .getMany()
```

<!-- EN -->
## Partial selection

<!-- ZH -->
## 部分选取

<!-- EN -->
If you want to select only some entity properties, you can use the following syntax:

<!-- ZH -->
如果你只想选取实体的部分属性，可以使用以下语法：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select(["user.id", "user.name"])
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select(["user.id", "user.name"])
    .getMany()
```

<!-- EN -->
This will only select the `id` and `name` of `User`.

<!-- ZH -->
这只会选取 `User` 的 `id` 和 `name`。

<!-- EN -->
## Using subqueries

<!-- ZH -->
## 使用子查询

<!-- EN -->
You can easily create subqueries. Subqueries are supported in `FROM`, `WHERE` and `JOIN` expressions. Example:

<!-- ZH -->
你可以轻松创建子查询。子查询在 `FROM`、`WHERE` 和 `JOIN` 表达式中都受支持。示例：

<!-- EN -->
```typescript
const qb = await dataSource.getRepository(Post).createQueryBuilder("post")

const posts = qb
    .where(
        "post.title IN " +
            qb
                .subQuery()
                .select("user.name")
                .from(User, "user")
                .where("user.registered = :registered")
                .getQuery(),
    )
    .setParameter("registered", true)
    .getMany()
```

<!-- ZH -->
```typescript
const qb = await dataSource.getRepository(Post).createQueryBuilder("post")

const posts = qb
    .where(
        "post.title IN " +
            qb
                .subQuery()
                .select("user.name")
                .from(User, "user")
                .where("user.registered = :registered")
                .getQuery(),
    )
    .setParameter("registered", true)
    .getMany()
```

<!-- EN -->
A more elegant way to do the same:

<!-- ZH -->
更优雅的等价写法：

<!-- EN -->
```typescript
const posts = await dataSource
    .getRepository(Post)
    .createQueryBuilder("post")
    .where((qb) => {
        const subQuery = qb
            .subQuery()
            .select("user.name")
            .from(User, "user")
            .where("user.registered = :registered")
            .getQuery()
        return "post.title IN " + subQuery
    })
    .setParameter("registered", true)
    .getMany()
```

<!-- ZH -->
```typescript
const posts = await dataSource
    .getRepository(Post)
    .createQueryBuilder("post")
    .where((qb) => {
        const subQuery = qb
            .subQuery()
            .select("user.name")
            .from(User, "user")
            .where("user.registered = :registered")
            .getQuery()
        return "post.title IN " + subQuery
    })
    .setParameter("registered", true)
    .getMany()
```

<!-- EN -->
Alternatively, you can create a separate query builder and use its generated SQL:

<!-- ZH -->
另外，你也可以创建一个独立的 query builder 并使用它生成的 SQL：

<!-- EN -->
```typescript
const userQb = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("user.name")
    .where("user.registered = :registered", { registered: true })

const posts = await dataSource
    .getRepository(Post)
    .createQueryBuilder("post")
    .where("post.title IN (" + userQb.getQuery() + ")")
    .setParameters(userQb.getParameters())
    .getMany()
```

<!-- ZH -->
```typescript
const userQb = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("user.name")
    .where("user.registered = :registered", { registered: true })

const posts = await dataSource
    .getRepository(Post)
    .createQueryBuilder("post")
    .where("post.title IN (" + userQb.getQuery() + ")")
    .setParameters(userQb.getParameters())
    .getMany()
```

<!-- EN -->
You can create subqueries in `FROM` like this:

<!-- ZH -->
你可以这样在 `FROM` 中创建子查询：

<!-- EN -->
```typescript
const userQb = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("user.name", "name")
    .where("user.registered = :registered", { registered: true })

const posts = await dataSource
    .createQueryBuilder()
    .select("user.name", "name")
    .from("(" + userQb.getQuery() + ")", "user")
    .setParameters(userQb.getParameters())
    .getRawMany()
```

<!-- ZH -->
```typescript
const userQb = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("user.name", "name")
    .where("user.registered = :registered", { registered: true })

const posts = await dataSource
    .createQueryBuilder()
    .select("user.name", "name")
    .from("(" + userQb.getQuery() + ")", "user")
    .setParameters(userQb.getParameters())
    .getRawMany()
```

<!-- EN -->
or using a more elegant syntax:

<!-- ZH -->
或者使用更优雅的语法：

<!-- EN -->
```typescript
const posts = await dataSource
    .createQueryBuilder()
    .select("user.name", "name")
    .from((subQuery) => {
        return subQuery
            .select("user.name", "name")
            .from(User, "user")
            .where("user.registered = :registered", { registered: true })
    }, "user")
    .getRawMany()
```

<!-- ZH -->
```typescript
const posts = await dataSource
    .createQueryBuilder()
    .select("user.name", "name")
    .from((subQuery) => {
        return subQuery
            .select("user.name", "name")
            .from(User, "user")
            .where("user.registered = :registered", { registered: true })
    }, "user")
    .getRawMany()
```

<!-- EN -->
If you want to add a subselect as a "second from" use `addFrom`.

<!-- ZH -->
如果你想添加一个子查询作为"第二个 from"，请使用 `addFrom`。

<!-- EN -->
You can use subselects in `SELECT` statements as well:

<!-- ZH -->
你也可以在 `SELECT` 语句中使用子查询：

<!-- EN -->
```typescript
const posts = await dataSource
    .createQueryBuilder()
    .select("post.id", "id")
    .addSelect((subQuery) => {
        return subQuery.select("user.name", "name").from(User, "user").limit(1)
    }, "name")
    .from(Post, "post")
    .getRawMany()
```

<!-- ZH -->
```typescript
const posts = await dataSource
    .createQueryBuilder()
    .select("post.id", "id")
    .addSelect((subQuery) => {
        return subQuery.select("user.name", "name").from(User, "user").limit(1)
    }, "name")
    .from(Post, "post")
    .getRawMany()
```

<!-- EN -->
## Hidden Columns

<!-- ZH -->
## 隐藏列

<!-- EN -->
If the model you are querying has a column with a `select: false` column, you must use the `addSelect` function in order to retrieve the information from the column.

<!-- ZH -->
如果你查询的模型中有 `select: false` 的列，你必须使用 `addSelect` 函数才能取回该列的信息。

<!-- EN -->
Let's say you have the following entity:

<!-- ZH -->
假设你有以下实体：

<!-- EN -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column({ select: false })
    password: string
}
```

<!-- ZH -->
```typescript
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @Column({ select: false })
    password: string
}
```

<!-- EN -->
Using a standard `find` or query, you will not receive the `password` property for the model. However, if you do the following:

<!-- ZH -->
使用标准的 `find` 或查询时，你不会收到该模型的 `password` 属性。不过，如果你这样做：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder()
    .select("user.id", "id")
    .addSelect("user.password")
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder()
    .select("user.id", "id")
    .addSelect("user.password")
    .getMany()
```

<!-- EN -->
You will get the property `password` in your query.

<!-- ZH -->
你就会在查询结果中得到 `password` 属性。

<!-- EN -->
`select: false` only controls what is loaded from the database on a read. The in-memory entity returned by `repository.save()` is not affected — any value you supply for a `select: false` column is preserved on both the returned entity and the original reference passed to `save()`. To re-read those columns from the database afterwards, run a subsequent query with `addSelect`.

<!-- ZH -->
`select: false` 只控制读取时从数据库加载什么。`repository.save()` 返回的内存中实体不受影响——你为 `select: false` 列提供的任何值都会保留在返回的实体以及传给 `save()` 的原始引用上。之后若要从数据库重新读取这些列，请再执行一次带 `addSelect` 的查询。

<!-- EN -->
## Querying Deleted rows

<!-- ZH -->
## 查询已删除的行

<!-- EN -->
If the model you are querying has a column with the attribute `@DeleteDateColumn` set, the query builder will automatically query rows which are 'soft deleted'.

<!-- ZH -->
如果你查询的模型中有带 `@DeleteDateColumn` 属性的列，query builder 会自动把"软删除"的行也查出来。

<!-- EN -->
Let's say you have the following entity:

<!-- ZH -->
假设你有以下实体：

<!-- EN -->
```typescript
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    DeleteDateColumn,
} from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @DeleteDateColumn()
    deletedAt?: Date
}
```

<!-- ZH -->
```typescript
import {
    Entity,
    PrimaryGeneratedColumn,
    Column,
    DeleteDateColumn,
} from "typeorm"

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number

    @Column()
    name: string

    @DeleteDateColumn()
    deletedAt?: Date
}
```

<!-- EN -->
Using a standard `find` or query, you will not receive the rows which have a value in that column. However, if you do the following:

<!-- ZH -->
使用标准的 `find` 或查询时，你不会收到该列有值的那些行。不过，如果你这样做：

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder()
    .select("user.id", "id")
    .withDeleted()
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder()
    .select("user.id", "id")
    .withDeleted()
    .getMany()
```

<!-- EN -->
You will get all the rows, including the ones which are deleted.

<!-- ZH -->
你就会得到所有行，包括已被删除的那些。

<!-- EN -->
## Common table expressions

<!-- ZH -->
## 公共表表达式

<!-- EN -->
`QueryBuilder` instances support [common table expressions](https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL#Common_table_expression) , if minimal supported version of your database supports them. Common table expressions aren't supported for Oracle yet.

<!-- ZH -->
如果你的数据库受支持的最低版本支持[公共表表达式](https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL#Common_table_expression)，`QueryBuilder` 实例也支持它们。Oracle 目前还不支持公共表表达式。

<!-- EN -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("user.id", "id")
    .addCommonTableExpression(
        `
      SELECT "userId" FROM "post"
    `,
        "post_users_ids",
    )
    .where(`user.id IN (SELECT "userId" FROM 'post_users_ids')`)
    .getMany()
```

<!-- ZH -->
```typescript
const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .select("user.id", "id")
    .addCommonTableExpression(
        `
      SELECT "userId" FROM "post"
    `,
        "post_users_ids",
    )
    .where(`user.id IN (SELECT "userId" FROM 'post_users_ids')`)
    .getMany()
```

<!-- EN -->
Result values of `InsertQueryBuilder` or `UpdateQueryBuilder` can be used in Postgres:

<!-- ZH -->
`InsertQueryBuilder` 或 `UpdateQueryBuilder` 的结果值可以在 Postgres 中使用：

<!-- EN -->
```typescript
const insertQueryBuilder = dataSource
    .getRepository(User)
    .createQueryBuilder()
    .insert({
        name: "John Smith",
    })
    .returning(["id"])

const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .addCommonTableExpression(insertQueryBuilder, "insert_results")
    .where(`user.id IN (SELECT "id" FROM 'insert_results')`)
    .getMany()
```

<!-- ZH -->
```typescript
const insertQueryBuilder = dataSource
    .getRepository(User)
    .createQueryBuilder()
    .insert({
        name: "John Smith",
    })
    .returning(["id"])

const users = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .addCommonTableExpression(insertQueryBuilder, "insert_results")
    .where(`user.id IN (SELECT "id" FROM 'insert_results')`)
    .getMany()
```

<!-- EN -->
## Time Travel Queries

<!-- ZH -->
## 时间旅行查询

<!-- EN -->
[Time Travel Queries](https://www.cockroachlabs.com/blog/time-travel-queries-select-witty_subtitle-the_future/) currently supported only in `CockroachDB` database.

<!-- ZH -->
[时间旅行查询](https://www.cockroachlabs.com/blog/time-travel-queries-select-witty_subtitle-the_future/)目前仅在 `CockroachDB` 数据库中受支持。

<!-- EN -->
```typescript
const repository = dataSource.getRepository(Account)

// create a new account
const account = new Account()
account.name = "John Smith"
account.balance = 100
await repository.save(account)

// imagine we update the account balance 1 hour after creation
account.balance = 200
await repository.save(account)

// outputs { name: "John Smith", balance: "200" }
console.log(account)

// load account state on 1 hour back
account = await repository
    .createQueryBuilder("account")
    .timeTravelQuery(`'-1h'`)
    .getOneOrFail()

// outputs { name: "John Smith", balance: "100" }
console.log(account)
```

<!-- ZH -->
```typescript
const repository = dataSource.getRepository(Account)

// 创建一个新账户
const account = new Account()
account.name = "John Smith"
account.balance = 100
await repository.save(account)

// 假设我们在创建 1 小时后更新了账户余额
account.balance = 200
await repository.save(account)

// 输出 { name: "John Smith", balance: "200" }
console.log(account)

// 加载 1 小时前的账户状态
account = await repository
    .createQueryBuilder("account")
    .timeTravelQuery(`'-1h'`)
    .getOneOrFail()

// 输出 { name: "John Smith", balance: "100" }
console.log(account)
```

<!-- EN -->
By default `timeTravelQuery()` uses `follower_read_timestamp()` function if no arguments passed. For another supported timestamp arguments and additional information please refer to [CockroachDB](https://www.cockroachlabs.com/docs/stable/as-of-system-time.html) docs.

<!-- ZH -->
默认情况下，如果不传参数，`timeTravelQuery()` 会使用 `follower_read_timestamp()` 函数。关于其他受支持的时间戳参数及更多信息，请参阅 [CockroachDB](https://www.cockroachlabs.com/docs/stable/as-of-system-time.html) 文档。

<!-- EN -->
## Debugging

<!-- ZH -->
## 调试

<!-- EN -->
You can get the generated SQL from the query builder by calling `getQuery()` or `getQueryAndParameters()`.

<!-- ZH -->
你可以通过调用 `getQuery()` 或 `getQueryAndParameters()` 从 query builder 拿到生成的 SQL。

<!-- EN -->
If you just want the query you can use `getQuery()`

<!-- ZH -->
如果你只想要查询本身，可以使用 `getQuery()`

<!-- EN -->
```typescript
const sql = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getQuery()
```

<!-- ZH -->
```typescript
const sql = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getQuery()
```

<!-- EN -->
Which results in:

<!-- ZH -->
结果是：

<!-- EN -->
```sql
SELECT `user`.`id` as `userId`, `user`.`firstName` as `userFirstName`, `user`.`lastName` as `userLastName` FROM `users` `user` WHERE `user`.`id` = ?
```

<!-- ZH -->
```sql
SELECT `user`.`id` as `userId`, `user`.`firstName` as `userFirstName`, `user`.`lastName` as `userLastName` FROM `users` `user` WHERE `user`.`id` = ?
```

<!-- EN -->
Or if you want the query and the parameters you can get an array back using `getQueryAndParameters()`

<!-- ZH -->
或者，如果你既想要查询又想要参数，可以用 `getQueryAndParameters()` 拿回一个数组

<!-- EN -->
```typescript
const queryAndParams = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getQueryAndParameters()
```

<!-- ZH -->
```typescript
const queryAndParams = await dataSource
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getQueryAndParameters()
```

<!-- EN -->
Which results in:

<!-- ZH -->
结果是：

<!-- EN -->
```typescript
;[
    "SELECT `user`.`id` as `userId`, `user`.`firstName` as `userFirstName`, `user`.`lastName` as `userLastName` FROM `users` `user` WHERE `user`.`id` = ?",
    [1],
]
```

<!-- ZH -->
```typescript
;[
    "SELECT `user`.`id` as `userId`, `user`.`firstName` as `userFirstName`, `user`.`lastName` as `userLastName` FROM `users` `user` WHERE `user`.`id` = ?",
    [1],
]
```
