Postgres-使用where子句+与众不同的左联接

时间:2019-06-10 23:19:30

标签: sql postgresql join

我想使用联接联接两个表

SELECT * FROM posts
LEFT JOIN voted ON posts.post_id = voted.id

哪个产生这个:

enter image description here

我如何使用以下方法创建查询

ORDER BY date_posted DESC FETCH FIRST 5 ROW ONLY 

在帖子表上以返回此结果

enter image description here

编辑1 :重复的post_id

我该怎么做,以使user_id列上的uuid仅为82411850-

enter image description here

编辑2 :感谢Linoff先生

SELECT p.post_id, p.date_posted, p.posted_by,
   v.user_id, v.votes
FROM posts p LEFT JOIN
 voted v
 ON p.post_id = v.id
 AND v.user_id = '82411580...'

ORDER BY p.date_posted DESC
FETCH FIRST 5 ROW ONLY ;

1 个答案:

答案 0 :(得分:1)

您的ID冲突。明确说明您要选择的列。

那么我认为您基本上有正确的逻辑:

SELECT p.post_id, p.date_posted, p.posted_by,
       v.user_id, v.votes
FROM posts p LEFT JOIN
     voted v
     ON p.post_id = v.id
ORDER BY p.date_posted DESC
FETCH FIRST 5 ROW ONLY ;