基于条件的postgresql查询

时间:2014-03-27 15:12:46

标签: postgresql

我有单桌。

示例:


id | pattern | currencyid|pricelist_id| comment|cost|start_date
1  | ^.123.* |         30|           2| USA    |2.00|2014-03-20 20:12:00
2  | ^.123.* |         30|           2| USA    |3.00|2014-03-22 20:12:00
3  | ^.123.* |         30|           2| KENYA  |1.00|2014-03-24 20:12:00
4  | ^.123.* |         22|           2| CANADA |4.00|2014-03-26 20:12:00
5  | ^.123.* |         22|           2| CANADA |5.00|2014-03-29 20:12:00
6  | ^.123.* |         30|           2| USA    |6.00|2014-03-30 20:12:00
7  | ^.123.* |         30|           2| USA    |6.00|2014-04-12 20:12:00
8  | ^.123.* |         22|           2| INDIA  |8.00|2014-04-12 20:12:00

必需的OutPut:

id | pattern | currencyid|pricelist_id| comment|old_cost|old_start_date     |NEW_COST|NEW_start_date
3  | ^.123.* |         30|           2| KENYA  |1.00    |2014-03-24 20:12:00|6.00    |2014-03-30 20:12:00
4  | ^.123.* |         22|           2| CANADA |4.00    |2014-03-26 20:12:00|8.00    |2014-04-12 20:12:00

说明:

此处首先,模式总是相同或不同。

  1. start_date> NOW()和最接近当前日期时间然后它将被视为new_start_Date,其成本称为new_cost

  2. start_date< NOW()和最接近当前日期时间然后它将被视为old_date,其成本为old_cost

  3. 添加其他条件。

  4. 步骤:

    我使用下面的查询获得所需的结果,这是一个非常漫长的过程。 如果我有一些额外的地方,那么它只在下面的查询中添加,这是不合适的,需要在所有下面的查询中添加,并根据该结果给我结果

    SELECT pattern, pricelist_id, currency_id
    FROM "table"
    WHERE pricelist_id=2
    GROUP BY "pattern", "pricelist_id", "currency_id";
    
    OUTPUT:
    pattern | pricelist_id|currencyid
     ^.123.*|            2|30
     ^.123.*|            2|22
    

    在php中使用foreach循环执行以下查询

    SELECT "id" as new_id, "cost" as new_cost, "start_date" as new_start_date
    FROM "table" 
    WHERE "pricelist_id" = '2' 
      AND "start_date" > '2014-03-28 10:35:26' 
      AND "pattern" = '^.123.*' 
      AND "currencyid" = '30' 
    ORDER BY "start_date" ASC
    LIMIT 1
    
    SELECT "id" as old_id, "cost" as old_cost, "start_date" as old_date, "comment"
    FROM "table" 
    WHERE "pricelist_id" = '2' 
      AND "start_date" <= '2014-03-28 10:35:26' 
      AND "pattern" = '^123.*' 
      AND "currencyid" = '30' 
    ORDER BY "id" desc, "start_date" DESC 
    LIMIT 1
    

    但它需要很长时间才能获得100万条记录,所以如果可能的话请建议我查询哪些记录顺利进行。

    是否可以通过单个PostgreSQL查询满足所有上述要求?

1 个答案:

答案 0 :(得分:0)

尝试使用WITH构造来获取计算数据:

with max_date as(select * from table where start_date < now() order by start_date desc limit 1),
min_date as(select * from table where start_date > now() order by start_date asc limit 1)
SELECT code, begin_time, (select code from max_date), (select code from min_date)
FROM table v 
where id in (
    (select id from max_date)
    union all
    (select id from min_date)
)