1

我确实意识到我面临的问题不是火箭科学,但我仍然没有找到任何有关解决此问题的信息。

我的数据库中有多个表 ( PSQL) 我想创建一个select查询来为我的应用程序创建报告功能。

这是我的查询:

select 
    s.id, s.name, st.name, p.firstname || ' ' || p.lastname, 
    f.name, f.store_date, bdt.name, bd.comment 
from  
    system s, systemstatus st, role w, person p, file f, 
    documenttype bdt, document bd 
where 
    w.system_id = s.id and 
    p.id = w.person_id and 
    st.id = s.status_id and 
    bd.system_id = s.id and 
    bd.file_id = f.id and 
    bd.type_id = bdt.id and 
    bd.role_id = w.id;

查询工作我得到300的行完全填充了我正在搜索的值。问题是我有关于表中的1000System。有可能没有PersonDocument可以与特定的 联系起来System

我想查看我的表中的所有行(我的意思是大约 1000 行) ,System当我无法链接Person或我希望该字段为空时(现在根本不显示)DocumentSystem

4

2 回答 2

5

Main part of the answer is - you need left outer join.
Additional parts of the answer - use ANSI join syntax and format your queries:

select
    s.id, s.name, st.name, p.firstname || ' ' || p.lastname, f.name,
    f.store_date, bdt.name, bd.comment
from system as s
    left outer join systemstatus as st on st.id= s.status_id
    left outer join role as w on w.system_id = s.id
    left outer join person as p on p.id = w.person_id
    left outer join document as bd on bd.system_id = s.id and bd.role_id = w.id
    left outer join documenttype as bdt on bdt.id = bd.type_id
    left outer join file as f on f.id = bd.file_id

Always remember that somebody will read your code someday (may be it will be future you :) ) - so readability counts!

于 2013-08-29T07:06:29.990 回答
0

您正在通过“where”子句连接查询中的表,这等于内部连接。相反,您应该将连接人员和文档表留给系统表,例如:

select * 
from system s
left join role w on w.system_id = s.id
left join person p on p.id = w.person_id
于 2013-08-29T07:01:00.163 回答