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


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语句),没有第一种语句好。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM