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教职员工和学生表中,候选人ID 是相同的,如何获取第一辆车的students记录staff。任何帮助......

4

2 回答 2

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 ║
╚════╩══════╝
于 2013-04-18T10:50:00.843 回答
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
于 2013-04-18T10:46:34.063 回答