我正在练习 自我连接 ,这是我编写查询时不了解的事情。
我有桌子 'employee'
'employee'
雇员表包含三个记录。
+-----+---------------+------------+ | id | employee | manager_id | +-----+---------------+------------+ | 1 | Ola | NULL | | 2 | Ahmed | 1 | | 3 | Tove | 1 | +----------+----------+------------+
最后一列manager_id是指使Ahmed和Tove成为Ola经理的第一列ID。
如果我这样写查询
SELECT emp.employee as NAME, manager.employee as MANAGER FROM employee as emp, employee as manager WHERE emp.id = manager.manager_id
结果使艾哈迈德和托夫经理。然而
SELECT emp.employee as NAME, manager.employee as MANAGER FROM employee as emp, employee as manager WHERE manager.id = emp.manager_id
正确无误,有人可以解释吗?
自联接就像内部联接,其中同一表的两个或更多实例通过公共数据类型的列/字段联接在一起。这种连接(内部连接)根据连接条件给出公共行。
雇员表包含三个记录。在这种情况下,
雇员为雇员:
员工为经理:
现在第一种情况:让我们尝试一下以了解不同之处:
选择emp.*,manager.* 从雇员作为emp,从雇员作为经理WHERE emp.id = manager.manager_id
emp.*
manager.*
+-----+---------------+------------+-----+---------------+------------+ | id | employee | manager_id | id | employee | manager_id | +-----+---------------+------------+-----+---------------+------------+ | 1 | Ola | NULL | 2 | Ahmed | 1 | | 1 | Ola | NULL | 3 | Tove | 1 | +----------+----------+------------+----------+----------+------------+
参见emp.id = manager.manager_id。因此,以emp.employee作为NAME从第一张表中给出Ola行,以manager.employee作为MANAGER从第二张表中给出Ahmed&Tove行。
现在第二种情况:让我们尝试一下以了解不同之处:
选择emp.*,manager.* 从雇员作为emp,从雇员作为经理WHERE manager.id = emp.manager_id
+-----+---------------+------------+-----+---------------+------------+ | id | employee | manager_id | id | employee | manager_id | +-----+---------------+------------+-----+---------------+------------+ | 2 | Ahmed | 1 | 1 | Ola | NULL | | 3 | Tove | 1 | 1 | Ola | NULL | +----------+----------+------------+----------+----------+------------+
参见manager.id = emp.manager_id。因此,作为emp.employee作为NAME从第一张表中给出了Ahmed&Tove的行,而作为MANAGER从第二个表中给出了Ola行的则是manager.employee。