0

所以我有 3 个表RecommendationArticleUser

推荐有 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)。

有任何想法吗?

4

1 回答 1

1

如果您还使用并且应该使用显式联接而不是隐式联接,则不需要子查询,CASE就可以了。这个查询应该让你开始:DISTINCT ONGROUP 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;

但仍有一些事情我不确定。你可以有两篇标题相同但ID不同的文章?在这种情况下,您可以选择具有较早/较晚推荐 submit_time 但如果没有推荐怎么办?您需要逻辑来了解如何选择不同的行以及最终如何对事物进行排序。

于 2013-03-14T12:57:05.170 回答