[英]Simple PostgreSQL Self Join
This is what my employee
table looks like where manager_id
is Foreign Key to the same table it references to employee_id
and indicates which employee has manager and who is.这就是我的employee
表的样子,其中manager_id
是它引用employee_id
的同一个表的外键,并指示哪个员工有经理以及谁是经理。
employee_id | first_name | last_name | manager_id
-------------+------------+-------------+------------
1 | Windy | Hays |
2 | Ava | Christensen | 1
3 | Hassan | Conner | 1
4 | Anna | Reeves | 2
5 | Sau | Norman | 2
6 | Kelsie | Hays | 3
7 | Tory | Goff | 3
8 | Salley | Lester | 3
I did self left join and the result was what was expected.我做了自我离开加入,结果是预期的。
SELECT
e.first_name || ' ' || e.last_name AS employee,
m.first_name || ' ' || m.last_name AS manager
FROM
employee e
LEFT JOIN employee m ON m.employee_id = e.manager_id;
employee | manager
-----------------+-----------------
Windy Hays |
Ava Christensen | Windy Hays
Hassan Conner | Windy Hays
Anna Reeves | Ava Christensen
Sau Norman | Ava Christensen
Kelsie Hays | Hassan Conner
Tory Goff | Hassan Conner
Salley Lester | Hassan Conner
(8 rows)
But this query gives me但是这个查询给了我
SELECT
e.first_name || ' ' || e.last_name AS employee,
m.first_name || ' ' || m.last_name AS manager
FROM
employee e
LEFT JOIN employee m ON m.employee_id = e.manager_id;
WHERE m.employee_id IS NULL;
employee | manager
------------+---------
Windy Hays |
(1 row)
So I don't understand why it returns something instead of nothing.所以我不明白为什么它会返回一些东西而不是什么都没有。 employee_id will never be a NULL... employee_id永远不会是 NULL...
http://sqlfiddle.com/#!17/6e6af/9 http://sqlfiddle.com/#!17/6e6af/9
employee_id will never be a NULL... employee_id 永远不会是 NULL...
The null
value comes from column e.manager_id
(not column m.employee_id
) - that's Windy Hays, the top employee in hierarchical tree. null
值来自e.manager_id
列(而不是m.employee_id
列) - 这是 Windy Hays,层次树中的顶级员工。
For this particular row, the left join
that attempts to retrieve the corresponding manager does not find a match - so now m.employee_id
is null
in the resultset.对于这个特定的行,尝试检索相应经理的left join
没有找到匹配项 - 所以现在m.employee_id
在结果集中是null
。
Maybe the where
clause you wanted to write is:也许你想写的where
子句是:
WHERE e.employee_id IS NULL
... Which indeed will return no rows, as one would expect. ...正如人们所期望的那样,这确实不会返回任何行。
You are doing a left join
from e
to m
.您正在从e
到m
进行left join
。
When there is no match, then the left join
still returns a row.当没有匹配时, left join
仍然返回一行。 What are the values for m
in the row?行中m
的值是多少? They are NULL
.它们是NULL
。
It is a convention that SQL uses NULL
to mean "missing match in outer join" (but there is really no alternative value).约定 SQL 使用NULL
来表示“外连接中的缺失匹配”(但实际上没有替代值)。
So, all columns for m
m in the row for Wendy Hayes will be NULL
.因此,Wendy Hayes 的行中m
的所有列都是NULL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.