数据库:查询结果中增加数据库不存在的字段的方法
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>
两个表,所以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语句),没有第一种语句好。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律