简单 SQL 查询,如果找不到匹配项则返回 null

Simple SQL Query to bring back null if no match found

编辑

我已经编辑了这个问题,让它更简洁一些,如果你看到我的编辑历史,你会看到我的努力和“我尝试过的”,但它增加了很多不必要的噪音并造成混乱所以这是输入和输出的摘要:

People:

ID | FullName
--------------------
1  | Jimmy
2  | John
3  | Becky

PeopleJobRequirements:

ID | PersonId | Title
--------------------
1  | 1        | Some Requirement
2  | 1        | Another Requirement     
3  | 2        | Some Requirement
4  | 3        | Another Requirement

输出:

FullName | RequirementTitle
---------------------------
Jimmy    | Some Requirement
Jimmy    | Another Requirement
John     | Some Requirement
John     | null
Becky    | null
Becky    | Another Requirement

每个人有 2 条记录,因为那是 table 中有多少不同的要求(不同基于 'Title')。

假设没有第三个table - 'PeopleJobRequirements'对每个人来说都是唯一的(一个人对很多要求),但是那里会有重复的Titles(有些人有相同的工作要求)。

对于最近的更新造成的任何混乱,我们深表歉意。

使用左连接,不需要任何子查询

select p.*,jr.*,jrr.* 
from People p left join
PeopleJobRequirements jr on p.Id=jrPersonId
left join JobRoleRequirements jrr p.id=jrr.PersonId

CROSS JOIN 为每个人获得相等的记录,LEFT JOIN 为匹配记录。

以下查询应该适用于您的场景

select p.Id, p.FullName,r.Title
FROM People p
cross join (select distinct title from PeopleJobRequirements )  pj
left join  PeopleJobRequirements r on  p.id=r.personid and pj.Title=r.Title
order by fullname

Online Demo

输出

+----+----------+---------------------+
| Id | FullName | Title               |
+----+----------+---------------------+
| 3  | Becky    | Another Requirement |
+----+----------+---------------------+
| 3  | Becky    | NULL                |
+----+----------+---------------------+
| 1  | Jimmy    | Some Requirement    |
+----+----------+---------------------+
| 1  | Jimmy    | Another Requirement |
+----+----------+---------------------+
| 2  | John     | NULL                |
+----+----------+---------------------+
| 2  | John     | Some Requirement    |
+----+----------+---------------------+

根据解释,People 和 PeopleJobRequirements tables 具有多对多关系(n 对 n)。 所以首先你需要另一个 table 来将这些与 table 联系起来。 首先执行此操作,然后进行完整连接即可。