我有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我想在transport表中检索VehicleId=1.中的学生和教职员工的记录,candidateIds在教职员工表和学生表中是相同的,如何在车辆一中获取students和staff的记录。任何帮助……
发布于 2013-04-18 18:50:01
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 ║
╚════╩══════╝发布于 2013-04-18 18:46:34
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 = 1https://stackoverflow.com/questions/16080799
复制相似问题