在PostgreSQL中的表列上执行foreach循环

时间:2019-02-11 15:47:46

标签: postgresql foreach

我需要遍历一个表列,并为每个值迭代一个简单的SELECT语句。

我得到带有以下语句的结果表:

SELECT event_id, count(event_id) as occurence
FROM event
GROUP BY event_id
ORDER BY occurence DESC
LIMIT 50

输出:

 event_id | occurence
---------------------
 1234567  | 56678
 8901234  | 86753

对于输出表中的每个event_id,我需要执行一个SELECT语句,例如:

SELECT * FROM event WHERE event_id = 'event_id from result row'

预期输出:

 event_id | even_type | event_time
 ----------------------------
 1234567  | .......   | .......
 1234567  | .......   | .......



 8901234  | .......   | .......
 8901234  | .......   | .......

换句话说:我需要从event_ids表中获取最近50个event,然后检索那些特定事件的所有可用数据。

我该如何实现?

2 个答案:

答案 0 :(得分:0)

可能有几种方法可以解决此问题,但这是一种方法:

SELECT  a.*, b.event_type, b.event_time
FROM
(
    SELECT event_id, count(event_id) as occurence
    FROM event
    GROUP BY event_id
    ORDER BY occurence DESC
    LIMIT 50
) a
JOIN event b ON (b.event_id = a.event_id)
;

您可以为所有列选择b。*,而不是我所说的“ b”中的特定列。

答案 1 :(得分:0)

甚至无需加入-只需使用窗口功能即可!参见下文:

SELECT *
FROM (
    SELECT  
        *, 
        COUNT(*) OVER(PARTITION BY event_id) AS event_count 
    FROM event 
) A 
ORDER BY event_count DESC
LIMIT 50