1、查询结果中增加数据库里不存在的字段的方法

  方法:SELECT '123' A, B ,C FROM TABLE

  解释: A为自定义的列,赋值为123。B,C为TABLE中原有的列。

  示例代码:

<select id="getRoleIds" resultType="UserRole">
  select ARRAY_AGG(company_id) roleIds, role_name roleName, 'company' as type from company_user where user_id = #{userId} group by role_name union
  select ARRAY_AGG(team_id) roleIds, role_name roleName, 'team' as type from team_user where user_id = #{userId} group by role_name
</select>
  上述语句我想要的是,一条语句获取2个不同表company_user和team_user里所有角色分别对应的 company_id 数组和 team_id 数组。
  两个表,所以union;不同角色,所以按 role_name 分组;由于角色相同,需要区分是哪个表即类型的角色,所以增加一个自定义列type(数据库里不存在的列)
  查询数据如下:
数据库:查询结果中增加数据库不存在的字段的方法

  还有一种查询语句如下:

select
  ARRAY_AGG(company_id) as compAdmins,
  (select ARRAY_AGG(company_id) as compMembers from company_user where user_id = 1073),
  (select ARRAY_AGG(team_id) as teamAdmins from team_user where user_id = 1073 and role_name = 'admin'),
  (select ARRAY_AGG(team_id) as teamMembers from team_user where user_id = 1073)
from company_user where user_id = 1073 and role_name = 'admin';

  查询结果如下:

数据库:查询结果中增加数据库不存在的字段的方法

  但是这种就是有多少角色,就得写 *2 的(select语句),没有第一种语句好。

相关文章:

  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
  • 2021-11-28
  • 2022-12-23
  • 2021-12-29
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-20
  • 2021-09-23
相关资源
相似解决方案