我有三张桌子,上面有学生,员工和学生。 Employees和Students中的“City”列是一个整数,指的是存储很多城市的Table City。
现在,我想要一份员工和学生表中每个人的列表,其中包含该人所在的城市。
例如:
Name | City --------------------------------- James (Employee) | London Jesus (Student) | London Daniel (Employee) | Manchester
答案 0 :(得分:2)
SELECT Name, 'Employee' AS 'Role', c.City
FROM Employees AS e
INNER JOIN Cities AS c ON e.City = c.id
UNION ALL
SELECT Student, 'Student' AS 'Role', c.City
FROM Students AS s
INNER JOIN Cities AS c ON s.City = c.id
我还建议更改一些字段名称:
Student
重命名为Name
City
重命名为CityID
City
重命名为CityID
答案 1 :(得分:1)
以下内容如何:
SELECT e.Name + '(Employee)', c.City
FROM Employees e
INNER JOIN Cities c ON e.City = c.id
UNION ALL
SELECT s.Student + '(Student)', c.City
FROM Students s
INNER JOIN Cities c ON s.City = c.id