表A中有一个属性可以告诉它将获得哪个表。
例如:
表A(信息)
InfoID | Type
表B(学生)
StudentID | Name | Course |
表C(雇员)
EmployeeID | Name | Company |
如果type = 1,则获取表B(学生)中的信息
InfoID | StudentID | Name | Course
否则获取表C(员工)中的信息
InfoID | EmployeeID| Name | Company
答案 0 :(得分:0)
类似的东西:
SELECT my_columns
FROM A
LEFT JOIN B ON A.InfoID = B.InfoID and A.type=1
LEFT JOIN C ON A.InfoID = C.InfoID and A.type <> 1
对于列,您可以使用CASE / WHEN:
SELECT A.InfoId,
MAX(CASE A.type = 1 THEN B.StudentID ELSE C.EmployeeID END) AS 'Employee/Student Id'
MAX(CASE A.type = 1 THEN B.Name ELSE C.Name END) AS 'Name'
MAX(CASE A.type = 1 THEN B.Course ELSE C.Company END) AS 'Company/Course'
FROM A
LEFT JOIN B ON A.InfoID = B.InfoID and A.type=1
LEFT JOIN C ON A.InfoID = C.InfoID and A.type <> 1
GROUP BY A.InfoID