如何通过加入获得单个结果?

时间:2012-11-24 16:04:36

标签: sql postgresql

使用postgres,我写了这个SQL请求:

SELECT projects.id
     , projects.title
     , comments.message as comment_message 
FROM "projects" 
RIGHT OUTER JOIN comments 
ON comments.project_id = projects.id
GROUP BY projects.id, comments.message

我有这样的结果:

 id |     title      | comment_message 
----+----------------+-----------------
  6 | simple project | simple comment
  6 | simple project | simple message

是否可以只获得第一个结果?我只想通过项目获得一个结果。

谢谢!

1 个答案:

答案 0 :(得分:1)

你可以写:

SELECT projects.id,
       projects.title,
       MIN(comments.message) AS comment_message 
  FROM "projects"
 RIGHT
 OUTER
  JOIN comments
    ON comments.project_id = projects.id
 GROUP
    BY projects.id
;