[英]how to use join for three tables
I have 3 tables. 我有3张桌子。 I want to fetch the employee details for those employees only in table3.
我想仅在表3中获取这些员工的员工详细信息。 But when i ran the query i am getting all the employees names from table1
但是当我运行查询时,我得到了table1中的所有员工姓名
Table1 and table 2 has many employees. 表1和表2有很多员工。
Table3 has only one employee name. Table3只有一个员工姓名。
Is the below query is correct? 以下查询是否正确? need some advise !!
需要一些建议!!
i am using left join because i want mis-match records also from table1 我正在使用左连接,因为我也希望来自table1的不匹配记录
select emp.emp_name, emp.dept, sal.salary
from table1 as emp
left join table2 as sal on emp.emp_name = sal.emp_name
and emp.emp_name in (select emp_name from table3)
Your query is not correct, given what you want it to do, as the and emp.emp_name in ...
part is part of the left join
condition and won't limit the rows in table1
. 根据您希望它执行的操作,您的查询不正确,因为
and emp.emp_name in ...
部分中的and emp.emp_name in ...
是left join
条件的一部分,并且不会限制table1
的行。 This is why you get all rows from table1
. 这就是你从
table1
获取所有行的原因。
To get all rows in table1
that have matches in table3
, plus the salary stuff (or null if missing) from table2
you can either change the second part of the left join
condition to a where clause or use an inner join
with table3
: 要得到所有行
table1
是在比赛table3
,加工资的东西(或空,如果丢失)从table2
,你可以改变的第二部分, left join
条件的WHERE子句或者使用inner join
与table3
:
-- using a where clause
select emp.emp_name, emp.dept, sal.salary
from table1 as emp
left join table2 as sal on emp.emp_name = sal.emp_name
where emp.emp_name in (select emp_name from table3);
-- or an inner join
select emp.emp_name, emp.dept, sal.salary
from table1 as emp
join table3 as t3 on emp.emp_name = t3.emp_name
left join table2 as sal on emp.emp_name = sal.emp_name;
For example if your tables had the following data: 例如,如果您的表具有以下数据:
table1: emp1, emp2, emp3
table2: emp1, emp2
table3: emp1, emp3
you would get: 你会得到:
emp_name salary
emp1 1000
emp3 NULL
Do Inner Join to get correct result 做内部加入以获得正确的结果
select
emp.emp_name,
emp.dept,
sal.salary
from table1 as emp
inner join table2 as sal on emp.emp_name = sal.emp_name and
emp.emp_name in (select emp_name from table3)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.