【问题标题】:Sequelize findAndCountAll with substring and distinct with multiple column使用子字符串对 findAndCountAll 进行续集,并使用多列进行区分
【发布时间】:2019-08-21 13:37:08
【问题描述】:

我正在尝试在 sequelize 中执行 findAndCountAll 操作。计数将基于 3 个不同列的组合。其中一列有子串操作(资源列)

我的客户表如下,

id, clientId, accountId, resource
1,  4f16,     2b18,      table::res/123
2,  4f16,     2b18,      chair::res/123

所以,我根据 clientId、accountIdresourceId(资源列上 res/ 之后的字符串)计算行数。因此,对于上述条目,我应该得到 1 作为计数,因为 clientId、accountId 和 resourceId 对于两个列都是相同的。

我的普通 postgres 查询是

select distinct c."accountId", c."clientId", substring("resource" from 'res/([^$]+)') 作为“resourceId” 从“客户”作为 c

我的 sequelize 查询现在看起来像没有不同的地方,

 const { rows, count} = await this.client.findAndCountAll({
  where: {
     clientId: clientId!
  },
  attributes: ['clientId', 'accountId',
    [fn('SUBSTRING', '"resource" from res/([^$]+)'), 'resId'],
    [fn('COUNT', col('id')), 'totalResource']],
  group: ['clientId', 'accountId', 'resource'],
   raw: true
});

我不确定如何执行该子字符串部分以及如何在 3 列上执行不同的操作。通过上面的查询,我得到 "SequelizeDatabaseError: function pg_catalog.substring(unknown) does not exist

【问题讨论】:

    标签: postgresql sequelize.js


    【解决方案1】:

    能够使用以下代码使其工作:

     const { rows, count} = await this.client.findAndCountAll({
          where: {
             clientId: clientId!
          },
          attributes: [
            fn('DISTINCT', col('clientId'), col('accountId'),  [fn('substring', col('resource') , 'res/([^$]+)'), 'resId']) ],
          group: ['clientId', 'accountId', 'resId'],
           raw: true
        });
    

    【讨论】:

      猜你喜欢
      • 2018-06-27
      • 1970-01-01
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 2013-08-29
      相关资源
      最近更新 更多