數據庫:查詢結果中增加數據庫不存在的字段的方法


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