使用 SQL 打印来自两个不同 table 的数据,但使用第三个 table 作为两者之间的 link
Using SQL to print data from two different tables but using a third table as a link between the two
我有 3 个 Table。员工、地点和部门。
我需要写一个 SQL 语句来显示来自 EMPLOYEES 的 first_name 和他们居住的城市。
链接的方式是这样的:
每个员工都有一个 Employee_ID,可以在 EMPLOYEES table 和 DEPARTMENTS table
中找到
DEPARTMENTS table 有一个 Location_ID 也存在于 LOCATIONS Table.
我会添加图片来更好地解释它,但我不知道该声明应该是什么样子。提前致谢。
您可以加入:
select e.first_name, l.city
from employees e
inner join departments d on d.employee_id = e.employee_id
inner join locations l on l.location_id = d.location_id
你都说了,只是 加入 那些表。先采样数据;您需要的查询从第 18 行开始。
SQL> with
2 employees (first_name, employee_id) as
3 (select 'Jack', 1 from dual union all
4 select 'Jill', 2 from dual union all
5 select 'Paul', 3 from dual
6 ),
7 departments (employee_id, location_id) as
8 (select 1, 10 from dual union all
9 select 2, 20 from dual union all
10 select 3, 30 from dual
11 ),
12 locations (location_id, city) as
13 (select 10, 'Narnia' from dual union all
14 select 20, 'Valhalla' from dual union all
15 select 30, 'Atlantis' from dual
16 )
17 --
18 select e.first_name, l.city
19 from employees e join departments d on e.employee_id = d.employee_id
20 join locations l on l.location_id = d.location_id
21 order by e.employee_id;
FIRS CITY
---- --------
Jack Narnia
Jill Valhalla
Paul Atlantis
SQL>
我有 3 个 Table。员工、地点和部门。
我需要写一个 SQL 语句来显示来自 EMPLOYEES 的 first_name 和他们居住的城市。
链接的方式是这样的:
每个员工都有一个 Employee_ID,可以在 EMPLOYEES table 和 DEPARTMENTS table
中找到DEPARTMENTS table 有一个 Location_ID 也存在于 LOCATIONS Table.
我会添加图片来更好地解释它,但我不知道该声明应该是什么样子。提前致谢。
您可以加入:
select e.first_name, l.city
from employees e
inner join departments d on d.employee_id = e.employee_id
inner join locations l on l.location_id = d.location_id
你都说了,只是 加入 那些表。先采样数据;您需要的查询从第 18 行开始。
SQL> with
2 employees (first_name, employee_id) as
3 (select 'Jack', 1 from dual union all
4 select 'Jill', 2 from dual union all
5 select 'Paul', 3 from dual
6 ),
7 departments (employee_id, location_id) as
8 (select 1, 10 from dual union all
9 select 2, 20 from dual union all
10 select 3, 30 from dual
11 ),
12 locations (location_id, city) as
13 (select 10, 'Narnia' from dual union all
14 select 20, 'Valhalla' from dual union all
15 select 30, 'Atlantis' from dual
16 )
17 --
18 select e.first_name, l.city
19 from employees e join departments d on e.employee_id = d.employee_id
20 join locations l on l.location_id = d.location_id
21 order by e.employee_id;
FIRS CITY
---- --------
Jack Narnia
Jill Valhalla
Paul Atlantis
SQL>