0

我有以下表格:

trendingtopic
  id
  name

trendingtopiccycle
  id
  trendingtopic_id(FK)

tweet
  id 
  text
  tt_cycle_id(FK)
  user_id(FK)

user
  id
  rank

我想知道是否有一种方法可以有效地检索每个热门话题的排名较高的用户发出的推文。

这是我当前的查询:

  SELECT tt."name",
  MAX(tu."actual_rank") AS rank,tu."name"
  FROM "trendingtopics_twitteruser" tu
  LEFT JOIN "trendingtopics_tweet" tw ON tu."id" = tw."user_id" 
  LEFT JOIN "trendingtopics_trendingtopiccycle" ttc ON tw."tt_cycle_id" = ttc."id"
  LEFT JOIN "trendingtopics_trendingtopic" tt ON ttc."tt_id" = tt."id" 
  GROUP BY tt."name"

它不起作用,因为根据 Postgresql:'“tu.name”必须出现在 GROUP BY 子句中或在聚合函数中使用'。

如果我将 tu."name" 添加到 GROUP BY 子句中,我最终会得到如下内容:

"106 & Park";0;"910Prince"
"106 & Park";0;"ActressAlexiss"
"106 & Park";0;"AmeliaThirlwall"
"106 & Park";0;"_ArielIvy"
"106 & Park";0;"_AyyeVce"
"106 & Park";0;"barcastuff"
"106 & Park";0.42141;"pareexo"
"106 & Park";0.0363;"khleosupporters"
"#15ThingsAboutMyCrush";0;"_ALoyalLady"
"#15ThingsAboutMyCrush";0.22275;"AmberrNikole"
"#15ThingsAboutMyCrush";0;"a_paigeturner"
"#15ThingsAboutMyCrush";0.33942018;"ArleneAndrea_xo"

但我想得到的是:

"106 & Park";0.42141;"pareexo"
"#15ThingsAboutMyCrush";0.33942018;"ArleneAndrea_xo"
4

3 回答 3

1

实际上,这可以很容易地在子查询中使用窗口函数来完成:

SELECT t."topic_name", t."rank", t."user_name"
FROM 
    (SELECT tt."name" AS topic_name, tu."actual_rank" AS rank, tu."name" AS user_name,
        row_number() OVER (PARTITION BY tt."name" ORDER BY tu."actual_rank" DESC) user_rank
    FROM "trendingtopics_trendingtopic" tt
    LEFT JOIN "trendingtopics_trendingtopiccycle" ttc ON ttc."tt_id" = tt."id"
    LEFT JOIN "trendingtopics_tweet" tw ON tw."tt_cycle_id" = ttc."id"
    LEFT JOIN "trendingtopics_twitteruser" tu ON tu."id" = tw."user_id") t
WHERE t."user_rank" = 1

此外,我对连接进行了重新排序,以便您从热门话题而不是 twitter 用户开始。由于您正在尝试为热门主题获取排名最高的用户,因此(至少对我而言)将其作为源表开始更有意义。

有关窗口函数和分区的更多信息,请访问此处:http ://www.postgresql.org/docs/8.4/static/tutorial-window.html

于 2012-08-03T14:02:31.913 回答
1

最快的解决方案可能是使用DISTINCT ON而不是窗口函数。

SELECT DISTINCT ON (tt."name")
    tt."name", tu."actual_rank" AS rank, tu."name"
  FROM "trendingtopics_twitteruser" tu
  LEFT JOIN "trendingtopics_tweet" tw ON tu."id" = tw."user_id" 
  LEFT JOIN "trendingtopics_trendingtopiccycle" ttc ON tw."tt_cycle_id" = ttc."id"
  LEFT JOIN "trendingtopics_trendingtopic" tt ON ttc."tt_id" = tt."id" 
  ORDER BY tt."name", tu."actual_rank" DESC;

顺便说一句,这是未经测试的,因为您没有提供语句来实际创建和加载您描述的表。如果您确实在问题中提供了此类内容,人们通常会在发布之前测试他们的答案,并且您不会有愚蠢的错误需要处理。

于 2012-08-03T19:37:11.577 回答
0
SELECT tt."name",
  MAX(tu."actual_rank") AS rank,MAX(tu."name") as name_1
  FROM "trendingtopics_twitteruser" tu
  LEFT JOIN "trendingtopics_tweet" tw ON tu."id" = tw."user_id" 
  LEFT JOIN "trendingtopics_trendingtopiccycle" ttc ON tw."tt_cycle_id" = ttc."id"
  LEFT JOIN "trendingtopics_trendingtopic" tt ON ttc."tt_id" = tt."id" 
  GROUP BY tt."name"
于 2012-08-03T13:34:52.080 回答