有没有办法 运行 使用 sequelize 的原始 JOIN?

Is there a way to run a raw JOIN with sequelize?

有没有办法 运行 使用 sequelize 的原始 JOIN?

下面是一个示例查询。我不能直接使用 JOIN,因为 table b 可以基于每个 group_id 包含来自 table a 的多条记录。我正在 运行ning 一个 WHERE id IN(子查询),这对于大型数据集来说很慢。比较时,JOIN 表现更好。但是,我在 sequelize 中看不到执行原始 INNER JOIN 的选项。

TABLE A
|---------------------|------------------|
|          id         |       name       |
|---------------------|------------------|
|          12         |     John Doe     |
|---------------------|------------------|


TABLE B
|---------------------|------------------|------------------|
|          id         |        a_id      |     group_id     |
|---------------------|------------------|------------------|
|          1          |         12       |       415        |
|---------------------|------------------|------------------|
|          2          |         12       |       416        |
|---------------------|------------------|------------------|
|          3          |         12       |       417        |
|---------------------|------------------|------------------|
SELECT a.*
FROM a
INNER JOIN (SELECT DISTINCT b.a_id FROM b WHERE b.group_id IN (1,2,4,5,6)) as b ON b.a_id = a.id
ORDER BY a.updated_at DESC;

在核心 sequelize 上,允许 2 次在 include

中使用关键字 required 进行连接
  1. required:true[default] 转换为 INNER JOIN。
  2. required:false 转换为 LEFT OUTER JOIN。

Reference for the same: https://sequelize.org/master/manual/eager-loading.html

我认为 sequelize 没有适合您使用的东西,请尝试使用原始查询(如果您认为您的查询已优化):

来自官方文档的代码片段:

const { QueryTypes } = require('sequelize');

await sequelize.query(
  'SELECT * FROM projects WHERE status = ?',
  {
    replacements: ['active'],
    type: QueryTypes.SELECT
  }
);

await sequelize.query(
  'SELECT * FROM projects WHERE status = :status',
  {
    replacements: { status: 'active' },
    type: QueryTypes.SELECT
  }
);

References for the same: https://sequelize.org/master/manual/raw-queries.html

我不得不使用一个 sub-query using sequelize literal 并且在大多数情况下效果很好。一年后,现在我在所有表中创建了一个单独的字段 group_id 并将所有权限数据移入其中。 join / sub-query 在我们的用例中太贵了。