简体   繁体   English

SQL 连接两个表

[英]SQL joining two tables

I have 2 tables employees(id and name) and salary(id, salary), the 1st has 4 rows and 2nd has 2 rows.我有 2 个表员工(id 和姓名)和工资(id,salary),第一个有 4 行,第二个有 2 行。

table 1            Table 2
id   Name         id    salary
1     Sue          1    10000 
2    Sarah         3     9000
3    Nick 
4    james 

I want a join as follows我想加入如下

id   Name     Salary
1     Sue     10000
2    Sarah    No Salary
3    Nick     9000
4    james    No salary

To get all rows from T1 when joining to table T2 that is lacking the rows 2 and 4 you need to use a left outer join .要在连接到缺少第 2 行和第 4 行的表T2时从T1获取所有行,您需要使用左外连接 For row 2 and 4 salary will be null.对于第 2 行和第 4 行,薪水将为空。

To replace the null value with something else you can use coalesce .要将空值替换为其他值,您可以使用coalesce Coalesce returns the first nonnull argument. Coalesce 返回第一个非空参数。

Since field salary is declared as an int field and you want No Salary as output where there is no salary you need to cast the int to a varchar before using it as an argument in coalesce.由于字段salary被声明为int字段,并且您希望No Salary作为输出,在没有salary 的情况下,您需要在int用作coalesce 中的参数之前将其转换为varchar

declare @T1 table(id int, name varchar(10))
declare @T2 table(id int, salary int)

insert into @T1 values(1, 'Sue')
insert into @T1 values(2, 'Sarah')
insert into @T1 values(3, 'Nick')
insert into @T1 values(4, 'james') 

insert into @T2 values(1, 10000)
insert into @T2 values(3, 9000)

select
  T1.id,
  T1.name,
  coalesce(cast(T2.salary as varchar(10)), 'No Salary') as salary 
from @T1 as T1
  left outer join @T2 as T2
    on T1.id = T2.id  

Result结果

id          name       salary
----------- ---------- ----------
1           Sue        10000
2           Sarah      No Salary
3           Nick       9000
4           james      No Salary
SELECT e.id, e.name , 
case
when s.salary is null then 'no salary'
else cast(s.salary as varchar)
end
FROM employees e LEFT JOIN salary s
ON e.id=s.id
order by e.id

Your goal is to list all employees, regardless of whether or not they have a listed salary, so you should be using a LEFT JOIN .你的目标是列出所有员工,不管他们是否有列出的薪水,所以你应该使用LEFT JOIN An inner join would potentially list salaries for employees that no longer have a listing in the Employee table and an implicit join (I believe) would be missing rows.内部连接可能会列出员工表中不再有列表的员工的薪水,而隐式连接(我相信)会丢失行。

Something like this should do what you need:像这样的事情应该做你需要的:

SELECT E.id, E.name, S.salary FROM Employees E LEFT JOIN Salary S ON E.id = S.id

This should do the trick.这应该可以解决问题。

SELECT e.id, e.name , s.salary FROM employees e 
LEFT JOIN salary s
ON e.id=s.id
ORDER BY e.id ASC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM