所以我有 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
'submit_time
列排序。
这是在 Postgres - 9.1.8 上。
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
一个?
我一直在尝试这样做一段时间,但无法弄清楚。我提出的查询要么将所有recommended
值返回为 0,要么返回重复的文章行(一个带有recommended=0
,另一个带有recommended=1
)。
有任何想法吗?