2013-04-18 70 views
1

我有3張表,學生,工作人員,運輸,在運輸表中有學生和工作人員誰有運輸記錄,並從CandidateType欄中區分。如果CandidateType = 0記錄必須來自員工表,如果CandidateType=1則記錄必須來自學生表。問題是兩個表中的連接列都具有相同的值。下面是我的表格的結構。在條件下加入不同的表

|Staff Table| 
------------------------- 
Id | Name | Designation | 
------------------------- 
1 | ABC | Teacher  | 
2 | xyz | Clerk  | 
3 | DDD | Teacher  | 

Student Table 
Id | Name | Class | 
------------------- 
1 | Ali | 5th | 
2 | Khan | 6th | 
3 | Jan | 6th | 

Transport Table 
Id | CandidateId | Candiadate Type | VehicleId 
---------------------------------------------- 
1 | 1   | 0    | 1 
2 | 3   | 1    | 1 
3 | 2   | 1    | 1 

我想要檢索的學生和工作人員的紀錄VehicleId=1.transport表candidateIds在工作人員和學生表相同,如何獲得studentsstaff記錄車輛之一。 任何幫助.....

回答

4
SELECT a.ID, 
     CASE WHEN CandidateType = 0 
      THEN b.Name 
      ELSE c.Name 
     END AS Name 
FROM Transport a 
     LEFT JOIN Staff b 
      ON a.CandidateID = b.ID 
     LEFT JOIN Student c 
      ON a.CandidateID = c.ID 
WHERE a.VehicleID = 1 

輸出

╔════╦══════╗ 
║ ID ║ NAME ║ 
╠════╬══════╣ 
║ 1 ║ ABC ║ 
║ 2 ║ Jan ║ 
║ 3 ║ Khan ║ 
╚════╩══════╝ 
+0

+1 SQLFiddle :) –

0
select * 
from Transport tr 
left join 
     Staff stf 
on  stf.Id = tr.CandidateId 
     and tr.CandidateType = 0 
left join 
     Student stu 
on  stu.Id = tr.CandidateId 
     and tr.CandidateType = 1