PostgreSQL - 需要一种方法来返回所有结果

时间:2015-05-06 20:39:50

标签: sql postgresql

目前,此查询仅返回“SFDC Contact ID”列中存在值的情况。好奇我如何更改查询以返回所有结果?我认为这需要一个外连接?

SELECT cmsuser.userid as "User ID", cmsuser.username as "Username", cmsuserprofile.value as "SFDC Contact ID"
FROM cmsuser, cmsuserprofile 
WHERE cmsuser.userid = cmsuserprofile.userid and fieldid = '5004';

2 个答案:

答案 0 :(得分:1)

您需要以下内容:

         SELECT cmsuser.userid as "User ID", 
                cmsuser.username as "Username", 
                cmsuserprofile.value as "SFDC Contact ID"
           FROM cmsuser
LEFT OUTER JOIN cmsuserprofile 
             ON cmsuser.userid = cmsuserprofile.userid 
           WHERE fieldid = '5004';

即使LEFT JOIN上没有匹配项,cmsuser也会返回cmsuserprofile(联接左侧的表格)中的所有记录。

JOINWHERE条件分开以使您的代码更易于理解和维护是一种很好的做法,这样您就可以更轻松地获得加入条件和什么只是where子句。

答案 1 :(得分:0)

据推测,alist *= 0位于个人资料表中。并且,“所有结果”表示“所有用户”。如果是这样,那么你确实需要这样的fieldid

left join

注意:您应该使用正确的显式SELECT u.userid as "User ID", u.username as "Username", p.value as "SFDC Contact ID" FROM cmsuser u LEFT JOIN cmsuserprofile p ON u.userid = p.userid and p.fieldid = '5004'; 语法。一个简单的规则:永远不要在join子句中使用逗号。