从与MS SQLSERVER相关的不同表中选择两列

时间:2017-05-06 12:09:47

标签: sql sql-server hibernate tsql

我正在从使用Hibernate转向SQL查询,而这个问题在我的SQL背景中相当困难:

我有下表和我有兴趣接收的字段:

:: PROFILE_TABLE FIELDS ::

ACCOUNT_FK> OWNER_FK

RECEIVER_FK> ACCOUNT_FK> _ OWNER_FK

我需要在ACCOUNT表中为此配置文件表中的每条记录获取OWNER,我无法想到这样做的方法,而没有一个我甚至无法想到的巨大的SQL查询现在。配置文件表有一个帐户字段和一个接收者字段,该字段还包含表中的帐户字段。

显然在Hibernate和java类中我只能使用

Profile.Account.Owner在数组中或者Profile.Receiver.Account.Owner在数组中,以检查每个配置文件中是否存在这两个所有者中的任何一个。

有人有想法吗?

从帐户表中选择所有者,其中account.id = profile.account_fk然后将其合并为接收者所需的多个联接?

1 个答案:

答案 0 :(得分:0)

没有看到有关所需结果和实际DDL的更多细节:

只需使用联接查找任一帐户的@owner_id

select
  p.*
from profile_table p
  inner join account a on p.account_id = a.account_id
  inner join receiver r on p.receiver_id = receiver_id
  inner join account ra on r.account_id = ra.account_id
where @owner_id in (a.owner_id,ra.owner_id)

union all

select
  p.*
from profile_table p
  inner join account a on p.account_id = a.account_id
where @owner_id = a.owner_id    
union all
select
  p.*
from profile_table p
  inner join receiver r on p.receiver_id = receiver_id
  inner join account ra on r.account_id = ra.account_id
where @owner_id = ra.owner_id

如果您必须通过owner中的其他列检查不是外键:

select
  p.*
  , o.name 
  , ro.name as receiver_name
from profile_table p
  inner join account a on p.account_id = a.account_id
  inner join owner o on a.owner_id = o.owner_id
  inner join receiver r on p.receiver_id = receiver_id
  inner join account ra on r.account_id = ra.account_id
  inner join owner ro on ra.owner_id = ro.owner_id
where @somecol in (o.somecol, ro.somecol)