在postgre中可以像这样制作foreach循环吗?

时间:2017-07-30 12:45:10

标签: sql postgresql pdo foreach

我想用pdo,wihout php计算一些东西。 我的查询看起来像这样:

WITH first_query as (
    SELECT date FROM users 
    WHERE user_id = 258; 
), second_query as (
   SELECT SUM(posts) FROM activity 
   WHERE date > (SELECT * FROM first_query)
   AND user_id = 258;
) 
SELECT user_id, date, first_time, (SELECT * FROM first_query), (SELECT * FROM second_query)
FROM users WHERE user_id = 258;

我想要执行此查询,从此查询中预告用户:

SELECT user_id FROM users 
WHERE country = 'PL';

实施例: 来自query = 1,4,6,66,676,34,678,234的用户; foreach这个用户,执行:

WITH first_query as (
    SELECT date FROM users 
    WHERE user_id = 258; 
), second_query as (
   SELECT SUM(posts) FROM activity 
   WHERE date > (SELECT * FROM first_query)
   AND user_id = 258;
) 
SELECT user_id, date, first_time, (SELECT * FROM first_query), (SELECT * FROM second_query)
FROM users WHERE user_id = 258;

其中user_id来自查询。 可以在查询中进行此操作吗?

也许我会在php中展示结果:

$users = 'select user_id from useres where something' // result as array

foreach ($users as $user_id) {
// execute query

    WITH first_query as (
        SELECT date FROM users 
        WHERE user_id = $user_id; 
    ), second_query as (
       SELECT SUM(posts) FROM activity 
       WHERE date > (SELECT * FROM first_query)
       AND user_id = $user_id;
    ) 
    SELECT user_id, date, first_time, (SELECT * FROM first_query), (SELECT * FROM second_query)
    FROM users WHERE user_id = $user_id;

}

我想在pdo中制作相同的循环。

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您希望在特定日期之后为给定的一组用户添加帖子总数。这更容易表达为JOINGROUP BY

假设users.user_id是唯一的(确实需要您的查询才能正常工作):

 SELECT u.*, SUM(a.posts)
 FROM users u JOIN
      activity a         
      ON a.user_id = u.user_id AND a.date > u.date
 WHERE u.user_id IN (1, 4, 6, 66, 676, 34, 678, 234)
 GROUP BY u.user_id;

或者,更具体地说:

 SELECT u.*, SUM(a.posts)
 FROM users u JOIN
      activity a         
      ON a.user_id = u.user_id AND a.date > u.date
 WHERE u.country = 'PL'
 GROUP BY u.user_id