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語句),沒有第一種語句好。