简体   繁体   English

如何在一张空表中使用三重 INNER JOIN?

[英]How to use triple INNER JOIN with one empty table?

Given is the following table:给定的是下表:

CREATE TABLE projects
(
    project_id integer,
    name character varying(50),
    owner_user integer NOT NULL,
    owner_org integer NOT NULL,
)

A project can be either owned by a user ( user_id ), OR by an organization ( org_id ) So either field is 0. So I do an INNER JOIN on projects , users , and organizations , but if the project is owned by a user (and currently no organization does exist at all), the result is empty.项目可以由用户user_id )拥有,也可以由组织( org_id )拥有,因此任何一个字段都是0。所以我对projectsusersorganizations进行了INNER JOIN,但如果项目归用户所有(并且目前根本不存在任何组织),结果为空。

Does NOT work不工作

SELECT *
FROM users u, projects p, organizations o
WHERE (p.owner_org != 0 AND o.org_id = p.owner_org) OR
      (p.owner_user != 0 AND u.user_id = p.owner_user);

Can anyone help me out?谁能帮我吗? If I leave out organization , the result is 1 row, as expected.如果我省略了organization ,结果是 1 行,正如预期的那样。

Works作品

SELECT *
FROM projects p, users u
WHERE (p.owner_user != 0 AND u.user_id = p.owner_user);

Learn to use proper, explicit, standard , readable JOIN syntax.学习使用正确的、明确的、标准的、可读的JOIN语法。

You seem to want:你似乎想要:

select *
from projects p left join
     users u 
     on p.owner_org = o.org_id left join
     organizations o
     on p.owner_user = u.user_id ;

I assume there is no id of 0 in the projects or organizations tables so the filtering is not necessary.我假设projectsorganizations表中没有0的 id,因此不需要过滤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM