1. 程式人生 > 實用技巧 >資料庫:查詢結果中增加資料庫不存在的欄位的方法

資料庫:查詢結果中增加資料庫不存在的欄位的方法

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