[英]How to join two tables to get combined result
I am trying to write a query, where I am retrieving employee data, fname, salary and unit no., where fname is 'Khalid' and his department name should be either 'IT' or 'Development'.我正在尝试编写一个查询,在其中检索员工数据、fname、薪水和单位编号,其中 fname 是“Khalid”,他的部门名称应该是“IT”或“Development”。
I am writing the query as我将查询写为
Select fname, salary, unitno from Employee Where fname = Khalid and Department.name = 'IT' or 'Development'
Both table have relationship based on Department number.两个表都具有基于部门编号的关系。
For Example:例如:
Employee Table:员工表:
Fname salary unitno Dno
Angel 2000 5 2
Jame 1000 3 2
Khalid 1500 6 4
Khalid 2500 9 2
Department Table:部门表:
Dnumber Name
2 IT
2 IT
4 Development
2 IT
Now the two table is in a relationship.现在这两个表处于关系中。 My query is not using Dno and Dnumber to connect them and finding the accurate result.我的查询没有使用 Dno 和 Dnumber 来连接它们并找到准确的结果。 Do I need to use JOIN here?我需要在这里使用 JOIN 吗? and how I know which is left table and which is right table?我怎么知道哪个是左表,哪个是右表?
Use inner join no need of left or right使用内部连接不需要左或右
Select fname, salary, unitno
from Employee
inner join Department
on Dno=Dnumber
Where fname = 'Khalid' and
(name = 'IT' or name='Development')
-- or your could write : name in ('IT','Development')
you can also use subquery as below:您还可以使用子查询,如下所示:
Select fname, salary, unitno
from Employee
Where fname = 'Khalid' and Dno in (
select Dnumber from Department where name = 'IT' or name='Development')
You can join and filter:您可以加入和筛选:
select e.fname, e.salary, e.unitno, d.name
from employee e
inner join department d on d.dnumber = e.dno
where e.fname = 'Khalid' and d.name in ('IT', 'Development')
Alternatively, you can also use a correlated subquery for filtering, if you don't need to display the department name:或者,如果不需要显示部门名称,也可以使用相关子查询进行过滤:
select e.fname, e.salary, e.unitno
from employee e
where e.fname = 'Khalid' and exists (
select 1 from department d where d.dnumber = e.dno and d.name in ('IT', 'Development')
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.