2017-05-06 65 views
-1

我使用Hibernate的SQL查詢的移動而這個問題是我在SQL背景相當困難:選擇兩個不同表中的列有關MS SQLSERVER

我有以下表,我在感興趣的領域接收:

:: PROFILE_TABLE場::

ACCOUNT_FK> OWNER_FK

RECEIVER_FK> ACCOUNT_FK> _ OWNER_FK

我需要在此配置文件表中的每條記錄的ACCOUNT表中獲得OWNER,我想不到一個沒有我現在甚至不能想到的巨大sql查詢的方法。個人資料表中有一個帳戶字段和一個接收者字段,其中還包含表中的帳戶字段。

顯然,在休眠和Java類,我可以只使用

Profile.Account.Owner是數組或Profile.Receiver.Account.Owner是在陣列檢測是否有任何這兩個業主的每個配置文件的存在。

任何人有想法嗎?

從帳戶表中選擇所有者account.id = profile.account_fk,然後將其合併爲接收方需要的多個連接?

+1

顯示示例表數據和預期的結果.. – GurV

回答

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) 
+0

Hi @SqlZim, 我試圖使用你的代碼,但沒有理解變量的使用,因爲它的值是從來沒有初始化,所以我收到0結果。 期望的結果將是業主的ID列表,然後我可以加入列表以檢查它是否存在;我想你也可以在同一個查詢中做到這一點,只是另一個包含所有者的表(如黑名單)。 表格如下: #PROFILE; [ACCOUNT_FK,RECEIVER_FK] #RECEIVER; [ACCOUNT_FK] #ACCOUNT; [OWNER_FK] – hitm4n66

相關問題