SQL在一列上有两个不同的表

时间:2015-02-23 21:02:40

标签: sql postgresql

我无法正确查询此查询。我正在使用Postgres并尝试查询用户查看的最后15个客户端。

client
id, name ...

impressions
imressionable_id, user_id, created_at ...

impressionable_id等于client_id,表格可以在此字段上加入。

我需要获取用户查看的最后15个DISTINCT客户端名称的列表,并按created_at日期订购DESC。问题是目前对展示次数表的查询将产生许多重复的条目,但每次查看客户时都会使用唯一的created_at时间戳创建新的展示次数记录。

所以,查询

select impressions.impressionable_id, created_at from impressions where user_id = 1 order by created_at DESC  

将产生:

  impressionable_id   created_at
        1            2014-11-14 21:44:47.705167 
        1            2014-11-14 21:32:15.411488 
        3            2014-11-14 18:43:26.020719 
        1            2014-11-14 18:42:15.974442
        5            2014-11-14 18:41:10.609617 
        3            2014-10-29 20:53:01.383896

我需要一个能给我的查询:

1    John Doe     2014-11-14 21:44:47.705167 
3    Jay Smith    2014-11-14 18:43:26.020719
5    Tim Jones    2014-11-14 18:41:10.609617 

等等。非常感谢任何帮助!

2 个答案:

答案 0 :(得分:1)

使用MAX()GROUP BY

select I.impressionable_id,c.name, MAX(I.created_at) as created_at 
from impressions JOIN
     client c ON c.id = I.user_id
group by impressionable_id,c.name
order by created_at DESC
limit 15;

答案 1 :(得分:1)

SELECT y.* FROM 
(
    SELECT 
        DISTINCT ON (x.id) x.id, x.name, x.created_at 
    FROM (SELECT c.id, c.name, i.created_at FROM clients c RIGHT JOIN impressions i ON c.id = i.user_id) x
) y 
ORDER BY y.created_at DESC LIMIT 15;