jack-zheng
1/4/2019 - 3:27 AM

sql, self join

sql, self join

Self Join

现在还不是很清楚 self join 存在的意义, 但是下面这个例子可能对理解有点帮助

-- 准别测试数据
sqlite> create table employee (name text, id integer, manager integer);

sqlite> insert into employee values ('jack', 1, 4);
sqlite> insert into employee values ('hurry', 2, 4);
sqlite> insert into employee values ('lucy', 3, 2);
sqlite> insert into employee values ('jm', 4, 0);

sqlite> select * from employee;
name        id          manager
----------  ----------  ----------
jack        1           4
hurry       2           4
lucy        3           2
jm          4           0

目标 显示 employee name + manage name

sqlite> SELECT a.name, b.name as Manager_name
   ...> FROM employee as a, employee as b
   ...> WHERE a.manage = b.id;
name        Manager_name
----------  ------------
jack        jm
hurry       jm
lucy        hurry

从理解上来说别把他想成一张表就行了, 逻辑上就不用这个绕了