PostgreSQL内部连接和左连接

时间:2018-11-13 16:51:46

标签: sql database postgresql join

我具有以下数据库结构,带有postgres 9.5:

create table users (
  id character varying(255), 
  email character varying(127)
);

create table org_users(
  id character varying(255), 
  user_id character varying(255), -- foreign key to users.id
  manager_org_user_id character varying(255) -- refers to org_users.id; same table referential dependency
);

insert into users (id, email) values ('111', 'user1@example.com');
insert into users (id, email) values ('222', 'user2@example.com');
insert into users (id, email) values ('333', 'manager@example.com');

insert into org_users (id, user_id, manager_org_user_id) values ('o1', '111', 'o3');
insert into org_users (id, user_id, manager_org_user_id) values ('o2', '222', 'o3');
insert into org_users (id, user_id, manager_org_user_id) values ('o3', '333', null);

我的桌子上有三个用户。 user1@example.comuser2@example.com是两个普通用户。 manager@example.com是他们的经理。现在,我要显示以下结构:

org_user_id, employee_user_id, employee_email, manager_org_user_id, manager_user_id, manager_email

我尝试使用以下sql查询,但它对syntax error near JOIN无效。有帮助吗?

select ou.id as employee_org_user_id,
    us.id as employee_user_id, 
    us.email as employee_email, 
    ou.manager_org_user_id as manager_org_user_id,
    u2.email as manager_email
from org_users ou 
    JOIN users us ON ou.user_id::text = us.id::text,
    LEFT JOIN org_users ou1 ON ou1.id::text = ou.manager_org_user_id::text
    LEFT JOIN users us2 ON ou1.user_id::text = us2.id::text;

2 个答案:

答案 0 :(得分:1)

删除空间,重命名u2.email,将演员表放到文本上:

select ou.id as employee_org_user_id,
    us.id as employee_user_id, 
    us.email as employee_email, 
    ou.manager_org_user_id as manager_org_user_id,
    us2.email as manager_email
from org_users ou 
    JOIN users us ON ou.user_id = us.id
    LEFT JOIN org_users ou1 ON ou1.id = ou.manager_org_user_id
    LEFT JOIN users us2 ON ou1.user_id = us2.id

答案 1 :(得分:1)

此查询解决了您的问题:

SELECT ou.id as employee_org_user_id,
       us.id as employee_user_id, 
       us.email as employee_email, 
       ou.manager_org_user_id as manager_org_user_id
FROM org_users ou JOIN users us ON ou.user_id = us.id

实时示例: