按主题划分的投票摘要,包括标签

我很想有一个数据探索器查询,可以列出某个类别中的所有主题以及每个主题的投票数。我对 SQL 查询是新手,找不到任何看起来足够接近可以让我修改的现有内容。

理想情况下,它看起来像这样:

主题 投票 回复 标签 关闭
示例主题 1 85 62 网站、iOS、Android
示例主题 2 79 45 网站

有人能帮我吗?如果这里不对,我很抱歉。这似乎是最接近的现有主题。

1 个赞

您好,欢迎您 @CarrieSeltzer :slight_smile:

您看这个可以吗?

-- [params]
-- int :category_id 

WITH tag_names AS (
    SELECT t.id topic_id,
    string_agg(tags.name, ', ' ORDER BY tags.name) AS "tags"
    FROM topics t
    JOIN topic_tags tt ON tt.topic_id = t.id
    JOIN tags ON tags.id = tt.tag_id
    GROUP BY t.id
)

SELECT t.created_at::date,
       dvtvc.topic_id,
       votes_count,
       t.posts_count,
       tn.tags,
       t.closed
FROM discourse_voting_topic_vote_count dvtvc
JOIN topics t ON t.id = dvtvc.topic_id
LEFT JOIN tag_names tn ON dvtvc.topic_id = tn.topic_id
WHERE t.category_id = :category_id
AND votes_count > 0
ORDER BY t.created_at DESC

1 个赞

是的,谢谢!这太棒了!我只需要做一个小的调整——如何让它在 CSV 导出中显示主题的名称(而不仅仅是主题 ID)?

1 个赞

我认为将 t.title 添加到 SELECT 中应该包含以下内容:

-- [params]
-- int :category_id 

WITH tag_names AS (
    SELECT t.id topic_id,
    string_agg(tags.name, ', ' ORDER BY tags.name) AS "tags"
    FROM topics t
    JOIN topic_tags tt ON tt.topic_id = t.id
    JOIN tags ON tags.id = tt.tag_id
    GROUP BY t.id
)

SELECT t.created_at::date,
       dvtvc.topic_id,
       t.title,
       votes_count,
       t.posts_count,
       tn.tags,
       t.closed
FROM discourse_voting_topic_vote_count dvtvc
JOIN topics t ON t.id = dvtvc.topic_id
LEFT JOIN tag_names tn ON dvtvc.topic_id = tn.topic_id
WHERE t.category_id = :category_id
AND votes_count > 0
ORDER BY t.created_at DESC

还有一个选项,可以在导出中包含指向该主题的工作链接,例如:

'https://meta.discourse.org/t/' || t.slug || '/' || t.id AS topic_url,
2 个赞

我感觉问这个问题很傻,但我真的弄不清楚该把这部分代码加到哪里。它应该放在哪里?

2 个赞

没关系。 :slight_smile: 它会放在这里:(只需将其更改为您自己的网站地址,而不是 Meta)

-- [params]
-- int :category_id

WITH tag_names AS (
    SELECT t.id topic_id,
    string_agg(tags.name, ', ' ORDER BY tags.name) AS "tags"
    FROM topics t
    JOIN topic_tags tt ON tt.topic_id = t.id
    JOIN tags ON tags.id = tt.tag_id
    GROUP BY t.id
)

SELECT t.created_at::date,
       dvtvc.topic_id,
       t.title,
       'https://meta.discourse.org/t/' || t.slug || '/' ||
       t.id AS topic_url,
       votes_count,
       t.posts_count,
       tn.tags,
       t.closed
FROM discourse_voting_topic_vote_count dvtvc
JOIN topics t ON t.id = dvtvc.topic_id
LEFT JOIN tag_names tn ON dvtvc.topic_id = tn.topic_id
WHERE t.category_id = :category_id
AND votes_count > 0
ORDER BY t.created_at DESC

2 个赞