Spring Data Jpa 当存在继承时,如何合并两个SQL查询以在一个表中显示结果

oxf4rvwz  于 2023-01-20  发布在  Spring
关注(0)|答案(2)|浏览(244)

我具有以下结构:用户是受理人和提交者的父项。提交者与请求具有一对多关系。请求与受理人具有多对多关系。
我想将以下2个查询合并到一个表中:

Select r.request_number, u.first_name as Assignee
from requests r, users u
join request_assignee ra on r.id = ra.request_id
join assignee a on u.id = ra.assignee_id;

Select requests.request_number as Request_Number, users.first_name as Submitter
from requests
Join submitter on requests.submitter_id = submitter.id
Join request_assignee on requests.id = request_assignee.request_id
join users on submitter.id = users.id;

请求可以有多个受理人。如何执行1次查询以在一个表中显示结果?
下面的图片可能对表格有帮助:

yvfmudvl

yvfmudvl1#

假设:输出Request NumberSubmitterAssignee
查询可以简化如下,原因是ASSIGNEESUBMITTER不是必需的,USERS加上两个不同角色的别名就足够了。

select r.request_number,
       s.first_name as submitter,
       a.first_name as assignee
  from requests r
  join request_assignee ra
    on r.id = ra.reqeust_id
  join users s
    on r.submitter_id = s.id
  join users a
    on ra.assignee_id = a.id;

当前数据模型:SUBMITTERASSIGNEE不提供附加信息。ID列是冗余的。

通过删除SUBMITTERASSIGNEE表建议的数据模型。

hmtdttj4

hmtdttj42#

也许,更改列名称并保持它们一致,然后尝试以下操作

Select r.request_number as Request_Number, u.first_name as Submitter
from requests r, users u
join request_assignee ra on r.id = ra.request_id
join assignee a on u.id = ra.assignee_id
unionall 
Select requests.request_number as Request_Number, users.first_name as Submitter
from requests
Join submitter on requests.submitter_id = submitter.id
Join request_assignee on requests.id = request_assignee.request_id
join users on submitter.id = users.id

相关问题