---
title: 使用查询构建器
sidebar_label: 查询构建器
---

来源：https://mikro-orm.io/docs/query-builder

:::info

要使用 `createQueryBuilder()` 方法，你需要从驱动包中导入 `EntityManager`。

```ts
import { EntityManager } from '@mikro-orm/mysql'; // 或任意其他 SQL 驱动包
```

:::

当你需要执行一些 SQL 查询、而不希望牵涉 ORM 的全部机制时，你可以自己拼装查询，也可以使用 `QueryBuilder` 辅助工具来为你构造查询：

```ts
const qb = em.createQueryBuilder(Author);
// 或使用 `em.qb()` 简写
// const qb = em.qb(Author);
qb.update({ name: 'test 123', type: PublisherType.GLOBAL }).where({ id: 123, type: PublisherType.LOCAL });

console.log(qb.getQuery());
// update `publisher2` set `name` = ?, `type` = ? where `id` = ? and `type` = ?

console.log(qb.getParams());
// ['test 123', PublisherType.GLOBAL, 123, PublisherType.LOCAL]

// 执行查询
const res1 = await qb.execute();
```

`QueryBuilder` 同样支持[智能查询条件](./28-query-conditions.md)。

<a id="executing-the-query"></a>
## 执行查询

`execute()` 方法会运行查询并返回原始结果（普通对象）。第一个参数控制结果格式：

```ts
const res1 = await qb.execute('all'); // 返回对象数组（默认）
const res2 = await qb.execute('get'); // 返回单个对象
const res3 = await qb.execute('run'); // 返回 { affectedRows: number, insertId: number, row: any }
```

<a id="execute-options"></a>
### 执行选项

第二个参数是一个选项对象，用于控制结果如何被处理：

```ts
interface ExecuteOptions {
  mapResults?: boolean;   // 将列名映射为属性名（默认：true）
  mergeResults?: boolean; // 将结果合并到标识映射中已有的实体实例上（默认：true）
  rawResults?: boolean;   // 返回未经转换的数据库原始值（默认：false）
}
```

**`mapResults`**——控制数据库列名到实体属性名的映射：

```ts
// Book 实体有 `createdAt` 属性，对应的数据库列为 `created_at`
const res1 = await qb.execute('get', { mapResults: true });
console.log(res1); // { createdAt: ... } —— 属性名

const res2 = await qb.execute('get', { mapResults: false });
console.log(res2); // { created_at: ... } —— 列名
```

**`mergeResults`**——当使用 `joinAndSelect` 得到连接结果时，控制是否把行合并为完整的实体图：

```ts
// mergeResults: true（默认）——行会被组合成实体图
const authors = await em.createQueryBuilder(Author, 'a')
  .select('*')
  .leftJoinAndSelect('a.books', 'b')
  .execute('all', { mergeResults: true });
// 返回 author 数组，其 books 数组已填充

// mergeResults: false ——每一行单独返回
const rows = await em.createQueryBuilder(Author, 'a')
  .select('*')
  .leftJoinAndSelect('a.books', 'b')
  .execute('all', { mergeResults: false });
// 返回扁平数组，每本书都会重复携带 author 数据
```

<a id="typed-raw-results"></a>
### 带类型的原始结果

`execute()` 的返回类型基于 `EntityDTO`——即普通对象，其中集合会被解包为数组，引用会被解包为其目标类型。当你使用 `select()` 或 `joinAndSelect()` 时，返回类型会自动反映所选中的字段与关联：

```ts
// 不带连接：Pick<EntityDTO<Author>, 'id' | 'email'>[]
const result1 = await em.createQueryBuilder(Author, 'a')
  .select(['a.id', 'a.email'])
  .execute();

// 带连接：EntityDTO<Loaded<Author, 'books', 'id' | 'email' | 'books.title'>>[]
const result2 = await em.createQueryBuilder(Author, 'a')
  .select(['a.id', 'a.email'])
  .leftJoinAndSelect('a.books', 'b', {}, ['title'])
  .execute();
```

如果你想放弃推断出的类型（例如在使用 `mapResults: false` 时，返回的是原始列名而非属性名），可以显式提供类型参数：

```ts
const result = await qb.execute<Dictionary[]>('all', false);
```

<a id="getting-entity-instances"></a>
### 获取实体实例

要获取完全水合的实体实例（受标识映射追踪），请使用 `getResult()` 或 `getSingleResult()`：

```ts
const book = await em.createQueryBuilder(Book).select('*').where({ id: 1 }).getSingleResult();
console.log(book instanceof Book); // true

const books = await em.createQueryBuilder(Book).select('*').getResult();
console.log(books[0] instanceof Book); // true
```

> `qb.getResultList()` 是 `qb.getResult()` 的别名。

<a id="mapping-raw-results-to-entities"></a>
## 将原始结果映射为实体

另一种从原始结果（这些结果不一定会映射到实体属性）创建实体的方式，是使用 `EntityManager` 的 `map()` 方法。它基本上是通过 `IDatabaseDriver.mapResult()`（把字段名转换为属性名——例如 `created_at` 转为 `createdAt`）与 `merge()`（把数据转换为实体实例并使其受管）来映射结果的快捷方式。

当你想使用第三方查询构建器（例如 Kysely）时，这个方法很方便，因为它们的结果不会被自动映射到实体属性：

```ts
const results = await em.execute<User[]>('select * from users where id = ?', [id]);
const users = results.map(user => em.map(User, user));

// 或使用 EntityRepository.map()
const repo = em.getRepository(User);
const users = results.map(user => repo.map(user));
```

<a id="implicit-joining"></a>
## 隐式连接

`QueryBuilder` 支持基于实体元数据自动连接：

```ts
const qb = em.createQueryBuilder(BookTag, 't');
qb.select('*').where({ books: 123 });

console.log(qb.getQuery());
// select `t`.*, `e1`.`book_tag_id`, `e1`.`book_uuid_pk`
// from `book_tag` as `t`
// left join `book_to_book_tag` as `e1` ON `t`.`id` = `e1`.`book_tag_id`
// where `e1`.`book_uuid_pk` = ?
```

这对多层嵌套同样有效：

```ts
const qb = em.createQueryBuilder(Author);
qb.select('*')
  .where({ books: { tags: { name: 'Cool' } } })
  .orderBy({ books: { tags: { createdBy: QueryOrder.DESC } } });

console.log(qb.getQuery());
// select `e0`.*
// from `author` as `e0`
// left join `book2` as `e1` on `e0`.`id` = `e1`.`author_id`
// left join `book2_to_book_tag2` as `e3` on `e1`.`uuid_pk` = `e3`.`book2_uuid_pk`
// left join `book_tag2` as `e2` on `e3`.`book_tag2_id` = `e2`.`id`
// where `e2`.`name` = ?
// order by `e1`.`tags` asc
```

目前这只对过滤（`where`）与排序（`orderBy`）可用，并且只会选中根实体。要填充它的关联关系，可以使用 [`em.populate()`](./29-populating-relations.md)。

<a id="explicit-joining"></a>
## 显式连接

另一种方式是通过 `join()`/`leftJoin()` 方法手动指定连接属性：

```ts
const qb = em.createQueryBuilder(BookTag, 't');
qb.select(['b.uuid', 'b.*', 't.*'], true)
  .join('t.books', 'b')
  .where({ 'b.title': 'test 123' })
  .limit(2, 1);

console.log(qb.getQuery());
// select distinct `b`.`uuid_pk`, `b`.*, `t`.*, `e1`.`book_tag_id`, `e1`.`book_uuid_pk` from `book_tag` as `t`
// join `book_to_book_tag` as `e1` ON `t`.`id` = `e1`.`book_tag_id`
// join `book` as `b` ON `e1`.`book_uuid_pk` = `b`.`uuid_pk`
// where `b`.`title` = ?
// limit ? offset ?
```

<a id="mapping-joined-results"></a>
## 映射连接结果

当你只使用 `join()` 或 `leftJoin()` 时，被连接的数据可用于过滤和排序，但它不会被映射到实体关联上。要把连接得到的关联正确地水合进实体，请使用 `joinAndSelect()` 或 `leftJoinAndSelect()`：

```ts
// 只用 leftJoin ——结果中 books 不会被填充
const authors1 = await em.createQueryBuilder(Author, 'a')
  .select('*')
  .leftJoin('a.books', 'b')
  .where({ 'b.title': { $like: '%TypeScript%' } })
  .getResultList();

console.log(authors1[0].books.isInitialized()); // false ——未填充！

// 使用 leftJoinAndSelect ——结果中 books 会被填充
const authors2 = await em.createQueryBuilder(Author, 'a')
  .select('*')
  .leftJoinAndSelect('a.books', 'b')
  .where({ 'b.title': { $like: '%TypeScript%' } })
  .getResultList();

console.log(authors2[0].books.isInitialized()); // true ——已填充！
console.log(authors2[0].books[0].title); // 可访问
```

你可以链式调用多个 `leftJoinAndSelect` 来填充嵌套关联：

```ts
// 填充 author 及其 books，以及每本书的 tags
const authors = await em.createQueryBuilder(Author, 'a')
  .select('*')
  .leftJoinAndSelect('a.books', 'b')
  .leftJoinAndSelect('b.tags', 't')
  .where({ 't.name': ['sick', 'sexy'] })
  .getResultList();
```

关键区别在于：

- `join()`/`leftJoin()`：连接表仅用于过滤/排序。结果只包含根实体数据。
- `joinAndSelect()`/`leftJoinAndSelect()`：连接并选中列，同时使用特殊别名（例如 `b__id`、`b__title`），水合器会借助它们把数据映射回实体关联。

<a id="type-safe-populated-relations"></a>
### 类型安全的已填充关联

`joinAndSelect` 与 `leftJoinAndSelect` 方法会增强返回类型，使其包含正确的 `Loaded` 类型提示。这意味着 TypeScript 知道哪些关联已被填充：

```ts
// 类型为 `Loaded<Author, 'books' | 'books.tags'>[]`
const authors = await em.createQueryBuilder(Author, 'a')
  .select('*')
  .leftJoinAndSelect('a.books', 'b')
  .leftJoinAndSelect('b.tags', 't')
  .getResultList();

// TypeScript 知道这些关联已被填充，允许直接访问
authors[0].books[0].tags[0].name; // OK

// 如果不使用 joinAndSelect，访问关联时会得到类型错误
```

请始终使用流式 API（链式方法），而不要先把 QueryBuilder 存到变量里——这样才能确保类型在每一步都被正确增强。

<a id="joining-sub-queries"></a>
## 连接子查询

有时你可能想连接某个关联，但又希望对查询有更多控制权。ORM 允许你用子查询覆盖连接目标，同时保留原始元数据用于水合：

```ts
const subquery = em.createQueryBuilder(Book, 'b')
  .where({ ... })
  .orderBy({ title: 'asc' }).limit(1);

const authors = await em.createQueryBuilder(Author, 'a')
  .select('*')
  // 把属性路径与子查询一起作为元组传入第一个参数
  .leftJoinAndSelect(['a.books', subquery], 'b')
  // 你可以在子查询连接之上继续连接更多关联
  .leftJoinAndSelect('b.tags', 't')
  .getResultList();
```

这会生成类似下面的查询：

```sql
select `a`.*,
  `b`.`id` as `b__id`, `b`.`title` as `b__title`, `b`.`author_id` as `b__author_id`, `b`.`publisher_id` as `b__publisher_id`,
  `t`.`id` as `t__id`, `t`.`name` as `t__name`
  from `author` as `a`
  left join (
    select `b`.*, `b`.price * 1.19 as `price_taxed`
    from `book` as `b`
    order by `b`.`title` asc
    limit 1
  ) as `b` on `b`.`author_id` = `a`.`id`
  left join `book_tags` as `e1` on `b`.`uuid_pk` = `e1`.`book_uuid_pk`
  left join `book_tag` as `t` on `e1`.`book_tag_id` = `t`.`id`
```

<a id="complex-where-conditions"></a>
## 复杂的 Where 条件

构造复杂查询条件有多种方式。你可以手写部分 SQL，也可以使用 `andWhere()`/`orWhere()`，或者提供条件对象：

<a id="using-custom-sql-fragments"></a>
### 使用自定义 SQL 片段

`WHERE` 查询或 `ORDER BY` 子句中的任何 SQL 片段都需要用 `raw()` 或 `sql` 包裹：

```ts
const users = em.createQueryBuilder(User)
  .select('*')
  .where({ [sql`lower(email)`]: 'foo@bar.baz' }) // sql 标签模板函数
  .orderBy({ [raw(`(point(loc_latitude, loc_longitude) <@> point(0, 0))`)]: 'ASC' }) // raw 辅助函数
  .getResultList();
```

这会生成如下查询：

```sql
select `e0`.*
from `user` as `e0`
where lower(email) = 'foo@bar.baz'
order by (point(loc_latitude, loc_longitude) <@> point(0, 0)) asc
```

更多内容请阅读[使用原始 SQL 查询片段](./33-raw-queries.md)章节。

<a id="custom-sql-in-where"></a>
### where 中的自定义 SQL

```ts
const qb = em.createQueryBuilder(BookTag, 't');
qb.select(['b.*', 't.*'])
  .leftJoin('t.books', 'b')
  .where('b.title = ? or b.title = ?', ['test 123', 'lol 321'])
  .andWhere('1 = 1')
  .orWhere('1 = 2')
  .limit(2, 1);

console.log(qb.getQuery());
// select `b`.*, `t`.*, `e1`.`book_tag_id`, `e1`.`book_uuid_pk` from `book_tag` as `t`
// left join `book_to_book_tag` as `e1` ON `t`.`id` = `e1`.`book_tag_id`
// left join `book` as `b` ON `e1`.`book_uuid_pk` = `b`.`uuid_pk`
// where (((b.title = ? or b.title = ?) and (1 = 1)) or (1 = 2))
// limit ? offset ?
```

<a id="andwhere-and-orwhere"></a>
### andWhere() 与 orWhere()

```ts
const qb = em.createQueryBuilder(BookTag, 't');
qb.select(['b.*', 't.*'])
  .leftJoin('t.books', 'b')
  .where('b.title = ? or b.title = ?', ['test 123', 'lol 321'])
  .andWhere('1 = 1')
  .orWhere('1 = 2')
  .limit(2, 1);

console.log(qb.getQuery());
// select `b`.*, `t`.*, `e1`.`book_tag_id`, `e1`.`book_uuid_pk` from `book_tag` as `t`
// left join `book_to_book_tag` as `e1` ON `t`.`id` = `e1`.`book_tag_id`
// left join `book` as `b` ON `e1`.`book_uuid_pk` = `b`.`uuid_pk`
// where (((b.title = ? or b.title = ?) and (1 = 1)) or (1 = 2))
// limit ? offset ?
```

<a id="conditions-object"></a>
### 条件对象

```ts
const qb = em.createQueryBuilder(Test);
qb.select('*').where({ $and: [{ id: { $nin: [3, 4] } }, { id: { $gt: 2 } }] });

console.log(qb.getQuery());
// select `e0`.* from `test` as `e0` where (`e0`.`id` not in (?, ?) and `e0`.`id` > ?)
```

<a id="count-queries"></a>
## 计数查询

要创建计数查询，可以使用 `qb.count()`，它会初始化一个带 `count()` 函数的 select 子句。默认情况下它会使用主键。

```ts
const qb = em.createQueryBuilder(Test);
qb.count().where({ $and: [{ id: { $nin: [3, 4] } }, { id: { $gt: 2 } }] });

console.log(qb.getQuery());
// select count(`e0`.`id`) from `test` as `e0` where (`e0`.`id` not in (?, ?) and `e0`.`id` > ?)

// 要拿到计数值，我们可以使用 `qb.execute()`
const res = await qb.execute('get');
const count = res ? +res.count : 0;
```

为了简化这一过程，你可以使用 `qb.getCount()` 方法。下面的代码是等价的：

```ts
const qb = em.createQueryBuilder(Test);
qb.select('*').limit(10, 20).where({ $and: [{ id: { $nin: [3, 4] } }, { id: { $gt: 2 } }] });

const count = await qb.getCount();
```

这同时会移除查询中已有的 limit 与 offset（QB 会在底层被克隆，因此调用 `getCount()` 不会改变原始 QB 的状态）。

<a id="pagination"></a>
## 分页

如果你想对 QueryBuilder 的结果进行分页，可以使用 `qb.getResultAndCount()` 方法。它返回一个有序元组：第一项是结果数组，第二项是忽略 limit 与 offset 子句后的条目总数。

```ts
const qb = em.createQueryBuilder(User);
qb.select('*')
  .where({ age: 18 })
  .limit(10);
const [results, count] = await qb.getResultAndCount();

console.log(results.length); // 最多 10，因为我们使用了 limit 子句
console.log(count); // 忽略 limit 与 offset 的总数，例如 1327
```

<a id="extracting-a-page-from-a-joined-result"></a>
### 从连接结果中提取一页

当你连接一个 to-many 关联并应用 `limit` 时，SQL 限制的是返回的总行数，而不是根实体的数量。由于笛卡尔积爆炸，这可能导致结果比预期更少。

MikroORM 会自动检测 to-many 连接与 `limit`/`offset` 的组合，并应用分页逻辑。它会把根实体的选择包裹在一个应用了 limit 的子查询中，然后再连接完整数据：

```ts
const authors = await em.createQueryBuilder(Author, 'a')
  .select('*')
  .leftJoinAndSelect('a.books', 'b')
  .limit(10)
  .offset(20)
  .getResultList();
```

这会生成带子查询的查询：

```sql
select `a`.*, `b`.*
  from (
    select `a`.*
    from `author` as `a`
    group by `a`.`id`
    limit 10 offset 20
  ) as `a`
  left join `book` as `b` on `a`.`id` = `b`.`author_id`
```

内层子查询按主键分组并应用 `limit`/`offset`，以得到正确数量的根实体。order by 子句会被包裹进 `min()` 聚合函数以配合分组。

**注意：** 如果你使用显式的 `groupBy()`，自动分页会被禁用。ORM 认为你希望完全掌控分组逻辑，因此会直接应用 limit：

```ts
const authors = await em.createQueryBuilder(Author, 'a')
  .select(['a.*', raw('count(b.id) as book_count')])
  .leftJoin('a.books', 'b')
  .groupBy('a.id')
  .limit(10)
  .getResultList();

// 不会包裹子查询 ——你的 groupBy 会被保留：
// select `a`.*, count(b.id) as book_count
//   from `author` as `a`
//   left join `book` as `b` on `a`.`id` = `b`.`author_id`
//   group by `a`.`id`
//   limit 10
```

如果你想显式禁用自动分页、并把 limit 直接应用到连接结果上，可以使用 `DISABLE_PAGINATE` 标志：

```ts
const authors = await em.createQueryBuilder(Author, 'a')
  .select('*')
  .leftJoinAndSelect('a.books', 'b')
  .limit(10)
  .setFlag(QueryFlag.DISABLE_PAGINATE) // limit 作用于行，而不是 author
  .getResultList();
```

<a id="using-having-with-aggregates"></a>
## 在聚合中使用 `having()`

使用 `groupBy()` 时，你可以通过 `having()` 过滤分组后的结果。`having()` 方法既接受带参数的字符串，也接受对象条件：

```ts
// 基于字符串的 having
const qb1 = em.createQueryBuilder(BookTag, 't')
  .select(['t.*', sql`count(t.id)`.as('book_count')])
  .leftJoin('t.books', 'b')
  .groupBy('t.id')
  .having('count(t.id) > ?', [5]);
```

```sql
select `t`.*, count(t.id) as `book_count`
from `book_tag` as `t`
left join `book_tags` as `e1` on `t`.`id` = `e1`.`book_tag_id`
group by `t`.`id`
having count(t.id) > 5
```

<a id="type-safe-having-with-raw-aliases"></a>
### 使用原始别名的类型安全 `having()`

当你在 select 中使用 `sql`...`.as('alias')` 创建带别名的聚合时，该别名会成为 `having()` 中一个类型安全的键：

```ts
const qb = em.createQueryBuilder(BookTag, 't')
  .leftJoin('t.books', 'b')
  .select(['t.*', 'b.*', sql`count(t.id)`.as('tag_count')])
  .groupBy(['b.uuid', 't.id'])
  .having({ tag_count: { $gt: 0, $lt: 100 } }); // 'tag_count' 会受到类型检查！
```

```sql
select `t`.*, `b`.*, count(t.id) as `tag_count`
from `book_tag` as `t`
left join `book_tags` as `e1` on `t`.`id` = `e1`.`book_tag_id`
left join `book` as `b` on `e1`.`book_uuid` = `b`.`uuid`
group by `b`.`uuid`, `t`.`id`
having `tag_count` > 0 and `tag_count` < 100
```

你也可以在 `having()` 中使用被连接表的别名：

```ts
const qb = em.createQueryBuilder(BookTag, 't')
  .leftJoin('t.books', 'b')
  .select(['t.*', sql`count(t.id)`.as('tags')])
  .groupBy(['b.uuid', 't.id'])
  .having({ 'b.title': { $like: '%test%' }, 't.name': { $ne: null } });
```

`andHaving()` 与 `orHaving()` 方法也可用于组合多个 having 条件。

<a id="aliasing-fields-with-as"></a>
### 用 `as` 为字段起别名

你可以使用 `as` 语法为任何被选中的字段起别名——包括 `@Formula` 属性：

```ts
// 字符串形式的 'as' 语法
const qb = em.createQueryBuilder(Book, 'b')
  .select(['b.title', 'b.priceTaxed as tax'])
  .where({ title: 'test' });
```

```sql
select `b`.`title`, `b`.`price` * 1.19 as `tax`
from `book` as `b`
where `b`.`title` = 'test'
```

对于公式属性，你也可以使用 `sql.ref().as()`：

```ts
const qb = em.createQueryBuilder(Book, 'b')
  .select(['b.title', sql.ref('b.priceTaxed').as('tax')])
  .where({ title: 'test' });
```

通过这两种机制创建的别名都会流入 `having()` 与 `orderBy()`，因此你可以对聚合别名做类型检查：

```ts
const qb = em.createQueryBuilder(FooBar, 'fb')
  .select(['fb.id', 'random as rnd'])
  .groupBy('fb.id')
  .having({ rnd: { $gt: 0 } }) // 'rnd' 会受到类型检查！
  .orderBy({ rnd: 'desc' });
```

> **注意：** 字段别名仅在 QueryBuilder 中受支持。自定义别名会破坏实体水合，因此在 `em.find()` 中不可用。

<a id="overriding-from-clause"></a>
## 覆盖 FROM 子句

你可以指定 `FROM` 子句中使用的表，如果已经指定过表名，它会被替换掉。这通常用于在 SQL 中指定一个子查询表达式。

```ts
const qb = em.createQueryBuilder(Book2);
qb.select('*').from(Author2).where({ id: { $gt: 2 } });

console.log(qb.getQuery());
// select `e0`.* from `author2` as `e0` where `e0`.`id` > 2;
```

你也可以像这样在 `FROM` 中使用子查询：

```ts
const qb1 = em.createQueryBuilder(Book2).where({ id: { $lte: new Date() } }).orderBy({ id: 'DESC' }).limit(10);
const qb2 = em.createQueryBuilder(qb1.clone())
qb2.select('*').orderBy({ id: 'ASC' });

console.log(qb2.getQuery());
// select `e1`.* from (select `e0`.* from `book2` as `e0` where `e0`.`id` <= ? order by `e0`.`id` desc limit ?) as `e1` order by `e1`.`id`;
```

要在 `SELECT` 语句中设置指向某张表的别名，按如下方式传入第二个参数：

```ts
const qb1 = em.createQueryBuilder(Book2, 'b1').where({ id: { $lte: new Date() } }).orderBy({ id: 'DESC' }).limit(10);
const qb2 = em.createQueryBuilder(qb1.clone(), 'b2')
qb2.select('*').orderBy({ id: 'ASC' });

console.log(qb2.getQuery());
// select `b2`.* from (select `b1`.* from `book2` as `b1` where `b1`.`id` <= ? order by `b1`.`id` desc limit ?) as `b2` order by `b2`.`id`;
```

<a id="using-sub-queries"></a>
## 使用子查询

你可以在 where 条件中使用子查询进行过滤：

```ts
const qb1 = em.createQueryBuilder(Book2, 'b').select('b.author').where({ price: { $gt: 100 } });
const qb2 = em.createQueryBuilder(Author2, 'a').select('*').where({ id: { $in: qb1 } });

console.log(qb2.getQuery());
// select `a`.* from `author2` as `a` where `a`.`id` in (select `b`.`author_id` from `book2` as `b` where `b`.`price` > ?)
```

对于 select 中的子查询，请使用 `qb.as(alias)` 方法：

> 动态属性（`booksTotal`）需要在实体级别定义（设置为 `persist: false`）。

```ts
import { sql } from '@mikro-orm/core';

const qb1 = em.createQueryBuilder(Book2, 'b').count('b.uuid', true).where({ author: sql.ref('a.id') }).as('Author2.booksTotal');
const qb2 = em.createQueryBuilder(Author2, 'a');
qb2.select(['*', qb1]).orderBy({ booksTotal: 'desc' });

console.log(qb2.getQuery());
// select `a`.*, (select count(distinct `b`.`uuid_pk`) as `count` from `book2` as `b` where `b`.`author_id` = `a`.`id`) as `books_total` from `author2` as `a` order by `books_total` desc
```

```ts
const qb3 = em.createQueryBuilder(Book2, 'b').count('b.uuid', true).where({ author: sql.ref('a.id') }).as('books_total');
const qb4 = em.createQueryBuilder(Author2, 'a');
qb4.select(['*', qb3]).orderBy({ booksTotal: 'desc' });

console.log(qb4.getQuery());
// select `a`.*, (select count(distinct `b`.`uuid_pk`) as `count` from `book2` as `b` where `b`.`author_id` = `a`.`id`) as `books_total` from `author2` as `a` order by `books_total` desc
```

当你想在谓词左侧使用子查询进行过滤时，需要先通过 `qb.withSubquery()` 注册它：

> 动态属性（`booksTotal`）需要在实体级别定义（设置为 `persist: false`）。在 `qb.withSubQuery()` 中你始终需要使用前缀（也就是 `a.booksTotal`）。

```ts
const qb1 = em.createQueryBuilder(Book2, 'b').count('b.uuid', true).where({ author: sql.ref('a.id') });
const qb2 = em.createQueryBuilder(Author2, 'a');
qb2.select('*').withSubQuery(qb1, 'a.booksTotal').where({ 'a.booksTotal': { $in: [1, 2, 3] } });

console.log(qb2.getQuery());
// select `a`.* from `author2` as `a` where (select count(distinct `b`.`uuid_pk`) as `count` from `book2` as `b` where `b`.`author_id` = `a`.`id`) in (?, ?, ?)
```

```ts
const qb3 = em.createQueryBuilder(Book2, 'b').count('b.uuid', true).where({ author: sql.ref('a.id') });
const qb4 = em.createQueryBuilder(Author2, 'a');
qb4.select('*').withSubQuery(qb3, 'a.booksTotal').where({ 'a.booksTotal': 1 });

console.log(qb4.getQuery());
// select `a`.* from `author2` as `a` where (select count(distinct `b`.`uuid_pk`) as `count` from `book2` as `b` where `b`.`author_id` = `a`.`id`) = ?
```

<a id="using-union-queries"></a>
## 使用 UNION 查询

你可以使用 `qb.union()` 与 `qb.unionAll()` 组合多个查询。这两个方法都返回一个 `QueryBuilder`，可以配合 `$in` 使用、传给 `qb.from()`，或者通过 `.getQuery()`、`.getParams()`、`.toQuery()`、`.toRaw()` 等转换。

`unionAll` 会保留所有行（包括重复行），而 `union` 会去重：

```ts
const qb1 = em.createQueryBuilder(Employee).select('id').where({ department: 'engineering' });
const qb2 = em.createQueryBuilder(Employee).select('id').where({ salary: { $gt: 100_000 } });

// UNION ALL（保留重复行）
const subquery = qb1.unionAll(qb2);
const qb = em.createQueryBuilder(Employee).select('*').where({ id: { $in: subquery } });

// UNION（去重）
const subquery2 = qb1.union(qb2);
const qb2b = em.createQueryBuilder(Employee).select('*').where({ id: { $in: subquery2 } });
```

你也可以串联两个以上的查询：

```ts
const qb3 = em.createQueryBuilder(Employee).select('id').where({ title: 'Manager' });
const combined = qb1.unionAll(qb2, qb3);
```

<a id="common-table-expressions-ctes"></a>
## 公共表表达式（CTE）

你可以通过 `with()` 与 `withRecursive()` 方法使用公共表表达式（CTE）。CTE 让你定义只在单条查询期间存在的具名临时结果集。

当你把一个 `QueryBuilder` 传给 `.with()` 时，实体类型会被记录在 `CTEs` 泛型参数中。随后用 `.from()` 传入 CTE 名称即可自动推断实体类型——`execute()`、`getResultList()` 以及字段引用都是完全类型化的，无需任何显式类型标注。

<a id="basic-cte"></a>
### 基础 CTE

```ts
const sub = em.createQueryBuilder(Author, 'a')
  .select(['a.id', 'a.name'])
  .where({ age: { $gte: 40 } });

// .from() 会从 CTE 推断实体类型 ——结果类型为 EntityDTOFlat<Author>[]
const rows = await em.createQueryBuilder(Author)
  .with('older_authors', sub)
  .select('*')
  .from('older_authors', 'oa')
  .execute();

rows[0].name; // string ——完全类型化，无需显式类型参数
```

```sql
with "older_authors" as (
  select "a"."id", "a"."name" from "author" as "a" where "a"."age" >= 40
)
select * from "older_authors" as "oa"
```

子查询会在调用 `.with()` 时立即编译——之后再修改子查询构建器不会反映到 CTE 中。

<a id="type-safe-from-and-field-access"></a>
### 类型安全的 `from()` 与字段访问

当 CTE 主体是一个带类型的 `QueryBuilder` 时，`.from()` 会把 CTE 名称解析为正确的实体类型。这意味着字段自动补全、`where()`、`select()` 与 `orderBy()` 都可以针对该 CTE 的实体工作：

```ts
const booksSub = em.createQueryBuilder(Book, 'b').select('*');

const results = await em.createQueryBuilder(Author, 'a')
  .with('recent_books', booksSub)
  .select(['rb.title', 'rb.id'])       // 针对 Book 做类型检查
  .from('recent_books', 'rb')          // 实体类型推断为 Book，别名为 'rb'
  .execute();

results[0].title; // string ——从 Book 实体推断而来
```

有多个 CTE 时，`.from()` 会为每个 CTE 名称解析出正确的实体：

```ts
const authorsCte = em.createQueryBuilder(Author, 'a').select('*');
const booksCte = em.createQueryBuilder(Book, 'b').select('*');

const qb = em.createQueryBuilder(Author)
  .with('authors_cte', authorsCte)
  .with('books_cte', booksCte);

// from('authors_cte') → 实体类型为 Author
const authors = await qb.select('*').from('authors_cte', 'ac').execute();

// from('books_cte') → 实体类型为 Book
const books = await qb.select('*').from('books_cte', 'bc').execute();
```

重复的 CTE 名称会抛出错误。

<a id="recursive-ctes"></a>
### 递归 CTE

递归查询（例如树形遍历）请使用 `withRecursive()`。在 MSSQL 上，它会生成普通的 `WITH`，因为 MSSQL 的 CTE 天然是递归的。

当 CTE 主体使用 `raw()` 时（在递归 CTE 中很常见），类型推断不可用——这种情况下请在 `execute()` 上使用显式类型参数：

```ts
const qb = em.createQueryBuilder(Author)
  .withRecursive('seq', raw('select 1 as n union all select n + 1 from seq where n < ?', [5]))
  .select('*')
  .from('seq', 's');

const rows = await qb.execute<{ n: number }[]>();
// [{ n: 1 }, { n: 2 }, { n: 3 }, { n: 4 }, { n: 5 }]
```

<a id="cte-options"></a>
### CTE 选项

可选的第三个参数支持 `columns` 与 `materialized` 选项：

```ts
// 列清单
const qb1 = em.createQueryBuilder(Author)
  .with('cte', sub, { columns: ['id', 'name'] })
  .select('*').from('cte');

// MATERIALIZED 提示（仅 PostgreSQL）
const qb2 = em.createQueryBuilder(Author)
  .with('cte', sub, { materialized: true })
  .select('*').from('cte');

// NOT MATERIALIZED 提示（仅 PostgreSQL）
const qb3 = em.createQueryBuilder(Author)
  .with('cte', sub, { materialized: false })
  .select('*').from('cte');
```

<a id="insert-from-select-insertfrom"></a>
## 从 select 插入（`insertFrom()`）

`qb.insertFrom(source, options?)` 会生成一条 `INSERT INTO ... SELECT` 语句，把源 `QueryBuilder` 产生的行复制进目标表——无需把这些行往返经过 Node.js。

它是驱动 [`em.clone()`](./10-entity-manager.md#cloning-entities) 的底层构建块，但你也可以直接用它来批量克隆、归档，或从另一条查询播种数据。

```ts
// 复制单行，所有列都从实体元数据自动推导
const source = em.createQueryBuilder(Book).where({ id: 1 });
await em.createQueryBuilder(Book).insertFrom(source).execute();

// 通过 SELECT 侧的 raw() 别名在复制时覆盖列值
const source = em.createQueryBuilder(Author)
  .select(['name', raw("'cloned@test.com'").as('email'), 'age', 'createdAt'])
  .where({ id: 1 });
await em.createQueryBuilder(Author).insertFrom(source).execute();

// 显式列清单 ——当 SELECT 中的 raw() 表达式没有 `.as()` 别名时很有用
await em.createQueryBuilder(Author)
  .insertFrom(source, { columns: ['name', 'email', 'age', 'createdAt'] })
  .execute();
```

<a id="column-resolution"></a>
### 列的解析

`insertFrom()` 按三个层级推导 `INSERT (col, col, ...)` 列清单，优先级从高到低：

1. **显式的 `columns` 选项**——用户提供的数组优先于其他一切。
2. **源查询上的显式 `select()`**——当源查询有自己的 `select(...)` 时，被选中的字段名（或 `.as()` 别名）会成为列清单。
3. **源查询上没有 `select()`**——MikroORM 会从实体元数据推导列清单，排除自增主键、生成列、公式属性、`persist: false` 以及 1:M / M:N（反向端）关联。内嵌属性与 M:1 外键列会被包含在内。

<a id="composable-with-onconflict-and-returning"></a>
### 可与 `onConflict()` 及 `returning()` 组合

返回的 `InsertQueryBuilder` 暴露的方法与常规的 `qb.insert()` 相同，因此你可以串联冲突处理器或 RETURNING 子句：

```ts
// 按唯一约束跳过重复项
const source = em.createQueryBuilder(Author).where({ id: 1 });
await em.createQueryBuilder(Author)
  .insertFrom(source)
  .onConflict('email').ignore()
  .execute();

// 返回插入的行（PostgreSQL / MSSQL / SQLite / libSQL）
const inserted = await em.createQueryBuilder(Author)
  .insertFrom(source)
  .returning('*')
  .execute();
```

该语句在所有 SQL 驱动上都能运行（SQLite、libSQL、PostgreSQL、MySQL、MariaDB、MSSQL）。MySQL / MariaDB 不支持 `RETURNING`，因此在这些驱动上请优先使用 `onConflict()` 或后续的 SELECT。

<a id="referring-to-column-in-update-queries"></a>
## 在更新查询中引用列

你可以使用静态的 `raw()` 辅助函数插入原始 SQL 片段，如下所示：

```ts
const qb = em.createQueryBuilder(Book);
qb.update({ price: raw('price + 1') }).where({ uuid: '123' });

console.log(qb.getQuery());
// update `book` set `price` = price + 1 where `uuid_pk` = ?
```

<a id="locking-support"></a>
## 锁支持

你可以通过 `qb.setLockMode()` 设置 `LockMode`。

```ts
const qb = em.createQueryBuilder(Test);
qb.select('*').where({ name: 'Lol 321' }).setLockMode(LockMode.PESSIMISTIC_READ);

console.log(qb.getQuery()); // 对于 MySQL
// select `e0`.* from `test` as `e0` where `e0`.`name` = ? lock in share mode
```

可用的锁模式：

| Mode                                 | Postgres                 | MySQL                            |
| ------------------------------------ | ------------------------ | -------------------------------- |
| `LockMode.PESSIMISTIC_READ`          | `for share`              | `lock in share mode`             |
| `LockMode.PESSIMISTIC_WRITE`         | `for update`             | `for update`                     |
| `LockMode.PESSIMISTIC_PARTIAL_WRITE` | `for update skip locked` | `for update skip locked`         |
| `LockMode.PESSIMISTIC_WRITE_OR_FAIL` | `for update nowait`      | `for update nowait`              |
| `LockMode.PESSIMISTIC_PARTIAL_READ`  | `for share skip locked`  | `lock in share mode skip locked` |
| `LockMode.PESSIMISTIC_READ_OR_FAIL`  | `for share nowait`       | `lock in share mode nowait`      |

可选地，你还可以通过第二个参数传入想要加锁的表别名列表：

```ts
const qb = em.createQueryBuilder(User, 'u');
qb.select('*')
  .leftJoinAndSelect('u.identities', 'i')
  .where({ name: 'Jon' })
  .setLockMode(LockMode.PESSIMISTIC_READ, ['u']);

console.log(qb.getQuery()); // 对于 Postgres
// select ...
//   from "user" as "u"
//   left join "identity" as "i" on "u"."id" = "i"."user_id"
//   where "u"."name" = 'Jon'
//   for update of "u" skip locked
```

<a id="collation"></a>
## 排序规则

你可以使用 `collation()` 方法为 `ORDER BY` 表达式设置排序规则。它会给 `ORDER BY` 子句中的**每一**列都追加 `COLLATE <collation>`：

```ts
const qb = em.createQueryBuilder(User);
qb.select('*')
  .collation('utf8mb4_general_ci')
  .orderBy({ name: 'asc' });

console.log(qb.getQuery());
// select `e0`.* from `user` as `e0`
//   order by `e0`.`name` collate `utf8mb4_general_ci` asc
```

要在 `WHERE` 条件中使用排序规则，请使用原始 SQL 片段：

```ts
const qb = em.createQueryBuilder(User);
qb.select('*')
  .where({ [sql`name collate utf8mb4_general_ci`]: 'john' });

console.log(qb.getQuery());
// select `e0`.* from `user` as `e0`
//   where name collate `utf8mb4_general_ci` = ?
```

<a id="using-kysely"></a>
## 使用 Kysely

MikroORM 原生构建 SQL 查询，并通过 [Kysely](https://kysely.dev/) 执行它们。你可以通过 `em.getKysely()` 方法获取已配置好的 Kysely 实例，并用它运行你自己的查询：

```ts
const kysely = em.getKysely();

const results = await kysely
  .selectFrom('author')
  .selectAll()
  .where('id', '>', 100)
  .execute();

// 把原始结果映射为实体
const entities = results.map(row => em.map(Author, row));
```

你也可以通过 `raw()` 辅助函数把 Kysely 查询构建器作为原始片段用在 MikroORM 查询中：

```ts
import { raw } from '@mikro-orm/postgresql'; // 或你的驱动包

const kysely = em.getKysely();
const kyselyQuery = kysely.selectFrom('author').select('id').where('active', '=', true);

const books = await em.find(Book, {
  author: { $in: raw(kyselyQuery) },
});
```

关于 Kysely 集成的更多细节，请参见 [Kysely](./34-kysely.md)。

<a id="migrating-from-knex"></a>
### 从 Knex 迁移

如果你正在从使用 Knex 的旧版本迁移，可以使用 `@mikro-orm/knex-compat` 包，它提供了一个 `raw()` 辅助函数，用于把 Knex 查询构建器实例转换为 ORM 的原始片段：

```ts
import { raw } from '@mikro-orm/knex-compat';

const knexQuery = knex.select('*').from('users');
const users = await em.find(User, { id: { $in: raw(knexQuery) } });
```

<a id="running-native-sql-query"></a>
## 运行原生 SQL 查询

你可以通过 `em.execute()` 运行原生 SQL：

```ts
const res = await em.execute('select 1 as count');
console.log(res); // res 是对象数组：`[ { count: 1 } ]`
```

该方法会处理日志记录、异常映射，并遵循当前的事务上下文。
