【问题标题】:Compare uuid and string on TypeORM query builder在 TypeORM 查询生成器上比较 uuid 和字符串
【发布时间】:2020-04-22 10:26:27
【问题描述】:

我想加入 2 个表,其中 user.id = photo.userId 但这里的问题是照片表上的 userId 是 varchar 并且无法更改。所以我做了一个queryBuilder加入,问题就在这里:

....
.where(user.id = photo.userId)
....

此查询抛出错误:运算符不存在:uuid = 字符变化

有什么办法可以做到吗?

注意:我的项目是一个 NestJS API,使用 TypeORM 和 Postgresql。

编辑 我已经有了照片结果并将其用于子查询:

query = query
         .where(qb => {
              const subQuery = qb.subQuery()
              .select('user.id')
              .from(User, 'user')
              .where('user.id = photo.userId)
              .getQuery();
              return 'EXISTS' + subQuery;
          });

【问题讨论】:

    标签: node.js postgresql typescript nestjs typeorm


    【解决方案1】:

    感谢您的帮助,最后我找到的最佳解决方案是创建一个 postgres 函数,如 here 所示,然后在代码中调用它,如下所示:

    query = query
             .where(qb => {
                  const subQuery = qb.subQuery()
                  .select('user.id')
                  .from(User, 'user')
                  .where('user.id = uuid_or_null(photo.userId))  // here
                  .getQuery();
                  return 'EXISTS' + subQuery;
              });
    

    【讨论】:

      【解决方案2】:

      https://www.postgresqltutorial.com/postgresql-cast/

      where (user.id::VARCHAR = photo.userId)

      【讨论】:

      • 我已经尝试过了,但由于某种原因它将 photo.userId 转换为 photo.userid,请注意 userid 上的小写(I 到 i)。
      • @hnakao11 然后把 photo.userId 作为 photo_user_id
      • @hnakao11 如果您将整个查询发送给我,我可以为您提供更多帮助。
      • 我编辑了问题,不知道你是否理解得更好
      【解决方案3】:

      首先,将 userId 中的“I”转换为“i”(从上到下)正是我们所期望的,因为除非双引号,否则标识符都是小写的。尽可能避免这种情况,因为在使用时您必须在 每次 使用标识符时使用双引号。
      其次,uuid 类型有一些奇怪和意想不到的格式化规则。您可以按预期将 string::uuid 与 uuid 进行比较,但 uuid::text 可能无法与 srting 进行比较。由于 uuid::text 将格式化为 hhhhhhhh-hhhh-hhhh-hhhh-hhhhhhhhhhh(其中 h 是十六进制数字)。如果存储为字符串,则通常会删除破折号。所以颠倒典型的顺序;将字符串转换为 uuid。请参见以下示例:

      create table id_uuid (id uuid, col1 text);
      create table id_str  (id text, col1 text 
      
      insert into id_uuid(id, col1) values(gen_random_uuid(),'Id defined as uuid');
      insert into id_str (id, col1)
        select replace(id::text,'-',''),'Id defined as string'
          from id_uuid;
      
      select * from id_uuid;
      select * from id_str;
      
      select * 
        from id_uuid u
        join id_str  s
          on (u.id::text = s.id);
      
      select * 
        from id_uuid u
        join id_str  s
          on (u.id = s.id::uuid); 
      

      【讨论】:

      • 所以,关于uuid到字符串的转换,反之亦然,这是一个很好的解释。一项要求是不能修改数据库。我仍然需要我的问题的答案,如果你能帮助我,但考虑我的问题......
      • 你不修改数据库,只修改查询。
      猜你喜欢
      • 2020-07-27
      • 2021-09-03
      • 1970-01-01
      • 2023-01-20
      • 2021-08-10
      • 1970-01-01
      • 2020-07-30
      • 2022-11-09
      • 1970-01-01
      相关资源
      最近更新 更多