如何重新编写此查询,以便我不排除没有标记的数据?

时间:2015-04-27 15:28:57

标签: sql postgresql

目前,此查询会排除报告中不包含标记的记录。有人可以帮我改变这个查询,以便返回所有记录,有或没有标签吗?

SELECT
  cmsdocument.internaldocid,
  cmsdocument.documentid,
  cmsdocument.versionid,
  cmsdocversion.title,
  string_agg(cmstag.tagname, ',')
FROM 
  public.cmsobjecttag,
  public.cmstag,
  public.cmsdocument,
  public.cmsdocversion,
  public.cmsuser
WHERE 
  cmsobjecttag.tagid = cmstag.tagid AND
  cmsobjecttag.objectid = cmsdocument.internaldocid AND
  cmsdocument.internaldocid = cmsdocversion.internaldocid AND
  cmsdocument.userid = cmsuser.userid AND
  cmsdocversion.state = 'published' AND
  cmsobjecttag.objecttype = '102'
GROUP BY 
  cmsdocument.internaldocid,
  cmsdocument.documentid,
  cmsdocument.versionid,
  cmsdocversion.title;

1 个答案:

答案 0 :(得分:2)

正如@notulysses评论的那样,你应该使用外连接。例如(未经测试):

SELECT
  d.internaldocid,
  d.documentid,
  d.versionid,
  dv.title,
  string_agg(t.tagname, ',')
FROM 
  public.cmsdocument d
  JOIN public.cmsdocversion dv ON d.internaldocid = dv.internaldocid AND dv.state = 'published'
  JOIN public.cmsuser u ON d.userid = u.userid
  LEFT JOIN public.cmsobjecttag ot ON d.internaldocid = ot.objectid AND ot.objecttype = '102'
  LEFT JOIN public.cmstag t ON t.tagid = ot.tagid
GROUP BY 
  d.internaldocid,
  d.documentid,
  d.versionid,
  dv.title;