Postgres group by with aggregate(所有对话的对话中的最后评论)

时间:2014-08-20 23:53:43

标签: postgresql group-by

我想在两个人之间的对话中得到最后的评论。

我的表格结构如下:

                                                          Table "public.comments"
   Column    |            Type             |                       Modifiers                       | Storage  | Stats target | Description 
-------------+-----------------------------+-------------------------------------------------------+----------+--------------+-------------
 id          | integer                     | not null default nextval('comments_id_seq'::regclass) | plain    |              | 
 body        | text                        | not null                                              | extended |              | 
 target_id   | integer                     |                                                       | plain    |              | 
 target_type | character varying(255)      |                                                       | extended |              | 
 created_at  | timestamp without time zone | not null                                              | plain    |              | 
 updated_at  | timestamp without time zone | not null                                              | plain    |              | 
 user_id     | integer                     |                                                       | plain    |              |

我的尝试:

SELECT
  comments.id,
  max(SELECT id comments.created_at),
  CASE 
  WHEN user_id   = 1 THEN CONCAT(user_id,'_',target_id) 
  WHEN target_id = 1 THEN CONCAT(target_id,'_',user_id)
  END
FROM comments
WHERE
  comments.user_id = 1
  OR
  (comments.target_type = 'User'
  AND
  comments.target_id = 1)
  GROUP BY 
    CASE 
    WHEN user_id   = 1 THEN CONCAT(user_id,'_',target_id) 
    WHEN target_id = 1 THEN CONCAT(target_id,'_',user_id)
    END

所以我想出了如何对评论进行分组,但是如何通过created_at进行排序并获取最新的ID和信息是我被困的地方。

0 个答案:

没有答案