2013-07-26 28 views
1

我試圖從數據庫中檢索兩個記錄,檢索當前部門和負責部門。SQL加入,檢索選定的記錄和條款

例如部門ID 13由部門ID來管理18

select dm.* from TblDepartment d 
join TblDepartment dm 
on d.ManagedBy = dm.id or d.id = dm.ManagedBy 
where d.id = 13 

其中加入做我需要使用檢索的兩個部門13和部門18部門信息的細節?

回答

1

嘗試follwoing:

select d.id Dept_Id, d.ManagedBy 
from 
    TblDepartment d 
where 
    d.id = 13 
union 
select dm.id Dept_Id , dm.ManagedBy 
from 
    TblDepartment d 
inner 
    join TblDepartment dm 
on d.ManagedBy = dm.id 
where 
    d.id = 13 
+0

這是完全一樣的我的答案 – Hogan

1

兩排

select 'Dept' as [type], * from 
TblDepartment d 
where d.id = 13 
union all 
select ' managed by' as [type], * from 
TblDepartment d 
where d.id = 18 

或者用一個連接和一個輸入:

select 'Dept' as [type], * from 
TblDepartment d 
where d.id = 13 
union all 
select ' managed by' as [type], m.* from 
TblDepartment d 
join TblDepartment m on d.ManagedBy = m.id and d.id = 13