所以我有3个表:Recommendation
,Article
和User
。
建议有4列:
id | integer
article_id |integer
user_id |integer
submit_time |integer
文章有3栏:
id | integer
title
url
我需要获取所有文章的列表,同时还使用新的推荐列注释每一行,如果相关用户推荐了该文章,则为1,否则为0。结果中不应有任何重复的Article
,我需要按Recommendation
的{{1}}列排序。
这是Postgres - 9.1.8。
submit_time
我正在将SELECT DISTINCT ON(t.title) t.title,
t.id, t.url,
MAX(recommended) as recommended
FROM (
SELECT submitter_article.title as title,
submitter_article.id as id,
submitter_article.url as url,
1 as recommended
FROM submitter_article, submitter_recommendation
WHERE submitter_recommendation.user_id=?
AND submitter_recommendation.article_id=submitter_article.id
UNION ALL
SELECT submitter_article.title as title,
submitter_article.id as id,
submitter_article.url as url,
0 as recommended
FROM submitter_article
) as t
GROUP BY t.title, t.id, t.url, recommended
传递给user id
我一直试图这样做一段时间,但无法弄明白。我提出的查询要么将所有?
值都返回0,要么返回重复的文章行(一个带有recommended
,另一个带有recommended=0
)。
有什么想法吗?
答案 0 :(得分:1)
您不需要子查询,CASE
会执行,DISTINCT ON
如果您还使用GROUP BY
则无用,您应该使用显式连接而不是隐式连接。这个查询应该让你开始:
SELECT DISTINCT ON (sa.title) sa.title, sa.id, sa.url,
(CASE
WHEN sr.id IS NULL THEN 0
ELSE 1
END) AS recommended
FROM submitter_article AS sa
LEFT JOIN submitter_recommendation AS sr ON sa.id=sr.article_id
AND sr.user_id=?
ORDER BY sa.title,sr.submit_time DESC;
但仍有一些我不确定的事情。你可以有两篇标题相同但不同的文章吗?在这种情况下,您可以选择具有早期/晚期建议submit_time的那个,但如果没有建议怎么办?您需要有关如何选择不同行以及如何最终订购事物的逻辑。