简体   繁体   English

从 Sequelize 中的另一个表中计数

[英]Count from another table in Sequelize

I've got to rewrite this SQL to Sequilize:我必须将这个 SQL 重写为 Sequilize:

SELECT table1.id, table1.name, 
    (SELECT COUNT(*) FROM table2 WHERE table2.t1_id = table1.id) AS t1_count 
FROM table1 WHERE .... LIMIT ..... OFFSET .....;

Thanks:)谢谢:)

To generate the exact SQL in your example use sequelize.literal() to generate the subquery.要在您的示例中生成准确的 SQL ,请使用sequelize.literal()生成子查询。

const result = await Table1.findByPk(id, {
  attributes: [
    'id', 
    'name',
    [
      sequelize.literal(`(
        SELECT COUNT(table2.id)
        FROM table2
        WHERE table2.id = table1.t1_id
      )`),
      't1_count',
    ],
  ],
  where: {
    // ...
  },
  limit: {
    // ...
  },
  offset: {
    // ...
  },
});

You can also do this by using a LEFT JOIN and then using sequelize.fn() to call COUNT() on the joined results.您也可以通过使用LEFT JOIN然后使用sequelize.fn()对连接的结果调用COUNT()来执行此操作。

const result = await Table1.findByPk(id, {
  attributes: [
    'id', 
    'name',
    [
      sequelize.fn('COUNT', sequelize.col('table2.id')),
      't1_count',
    ],
  ],
  include: {
    model: Table2,
    attributes: [],
    where: {
      id: {
        [Op.col]: sequelize.col('table1.t1_id'),
      },
    },
    required: false,
  },
  where: {
    // ...
  },
  limit: {
    // ...
  },
  offset: {
    // ...
  },
});
SELECT id, name, COUNT(table2.id)
FROM table1
LEFT JOIN table2 ON table2.id = table1.t1_id 
WHERE .... LIMIT ..... OFFSET .....;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM