Postgresql

如何在子查詢的where條件下獲取列值?

  • July 31, 2019

我試圖通過子查詢在 where 條件下獲取不同的值列表,但它在結果集中顯示 0 行。這是我的查詢。

SELECT a.topic_id, t.id as topicid, t.value as value, t.topic as topic, COUNT(c.topic_id) as count 
FROM post_topics a 
JOIN posts b ON a.post_id = b.id 
JOIN post_topics c on a.post_id = c.post_id 
JOIN topics t on c.topic_id = t.id
--with test as (select id from topics)
--WHERE (a.topic_id::varchar) in (select id from topics_temp)
**WHERE (a.topic_id::varchar) in (SELECT STRING_AGG(id, ',') FROM topics_temp)
AND (t.id::varchar) NOT IN (SELECT STRING_AGG(id, ',') FROM topics_temp)**
--AND  (t.id::varchar)  NOT IN (select id from topics_temp)
and (b.date_posted > (('now'::text)::date - '6 mons'::interval))
GROUP BY t.id, c.topic_id,a.topic_id 
ORDER BY count DESC;

結果集: 上述查詢的結果

原始查詢:我在下面的查詢中直接傳遞主題 ID,計數不同。

SELECT t.id as topic_id, t.value as value, t.topic as topic, COUNT(c.topic_id) as count 
FROM post_topics a 
JOIN posts b ON a.post_id = b.id 
JOIN post_topics c on a.post_id = c.post_id 
JOIN topics t on c.topic_id = t.id --AND t.topic = 'cuisine'
WHERE a.topic_id = 'c108200f-e4dc-415e-9150-3f6c74b879e2' 
AND t.id != 'c108200f-e4dc-415e-9150-3f6c74b879e2' 
AND (b.date_posted > (('now'::text)::date - '6 mons'::interval)) 
    GROUP BY t.id, c.topic_id 
    ORDER BY count DESC 
    LIMIT 10;

查詢特定主題

所以在 where 子句中,我提到了兩個條件 IN 和 Not IN 條件。Topics_temp 有 8110 個不同的主題名稱,我應該在每個主題中執行上述連接。但我不知道如何為查詢中的每個主題執行上述邏輯。任何人都可以幫我解決這個問題。最近兩天我正在努力解決這個問題。

查詢邏輯 原始查詢: 表資訊: Posts: post_id, url, dateposted |Topics: topic_id,topic,value |Post_topic: post_id,topic_id

首先,它從 where 子句中獲取主題 id,並開始與 post 表的第一次連接 - 它選擇與該主題 id 相關的所有文章。在第二個連接中 - 對於從先前查詢中檢索到的文章,它會轉到 post_topics 表以再次獲取相關主題。現在在第三次連接中,它計算我們從第二次連接中獲得的每個主題的計數。此主題 id 的輸出是 ‘c108200f-e4dc-415e-9150-3f6c74b879e2’ 已共享。輸出中的第一列是我們第三次加入的相關主題 ID。

我得到了我的查詢的修復程序。它只是與主題表的另一個連接。

SELECT a.topic_id as main_topic, t.id as topicid, t.value as value, t.topic as topic, COUNT(c.topic_id) as count
FROM post_topics a
JOIN posts b ON a.post_id = b.id
JOIN post_topics c on a.post_id = c.post_id
JOIN topics t on c.topic_id = t.id
**JOIN topics t2 on t2.id = a.topic_id and (t.id) <> (t2.id)**
WHERE (b.date_posted > (('now'::text)::date - '6 mons'::interval))
AND LOWER(b.source) = 'instagram'
GROUP BY t.id, c.topic_id,a.topic_id
ORDER BY c.topic_id,count DESC;

對我來說,不清楚您想要實現什麼,也許您可以在問題中重新表述您的目標。(也許我可以編輯我的答案來進行查詢)

正如我所不理解的那樣,您想匯總一些關於給定主題的表格。

為了使您的查詢更清晰,我建議使用通用表表達式並製作一些臨時表。你也可以看看分區

希望這能有所幫助。

引用自:https://dba.stackexchange.com/questions/244183