【问题标题】:loop through arrays in postgresql table return based on condition and array element position根据条件和数组元素位置循环遍历postgresql表中的数组返回
【发布时间】:2019-09-27 01:56:56
【问题描述】:

我在 posgresql 数据库的表中有以下行:

INSERT INTO "public"."position" ("id",
                                 "layout_id",
                                 "dining_table_id",
                                 "x_position",
                                 "y_position",
                                 "translate_x",
                                 "translate_y",
                                 "rotation",
                                 "start_timestamps",
                                 "end_timestamps")
VALUES (683, 32, 683, 1288, 0, E'{0,25}', E'{134,-98}', 0, E'{"2019-03-05 10:24:00","2019-04-05 10:24:00"}', E'{"2019-03-05 21:00:00","2019-04-05 21:00:00"}');

我想做一个查询,它返回我:

  • x_position
  • y_position
  • 旋转

  • translate_x
  • translate_y

但只有在满足以下条件时才在这些列中:

如果给定的时间戳(来自前端并且应该是查询条件的一部分)大于或等于 start_timestamps 并且小于 end_timestamps 数组元素,它们在数组中的位置与translate_x 和 translate_y 数组元素。

例如,如果给定的时间戳是:2019-03-05 12:00:00 translate_x 列的数组元素,值为 0(位置 0)和 应该返回值为 134(位置 0)的 translate_y 列的数组元素,因为 2019-03-05 12:00:00 小于 end_timestamps 列数组元素(位置 0)并且大于或等于 start_timestamps 列数组元素(位置 0)。

我的问题是如何相应地查询表? (我希望我的表结构有意义)

我的尝试:

const result = await this.db.query(`
SELECT 
       p.x_position,
       p.y_position,
       p.rotation,
FROM POSITION p 
DECLARE 

s int8 := 0;
x int;

BEGIN
FOR x IN s..p.start_timestamps.length LOOP IF p.start_timestamps[x] <= $1
AND p.end_timestamps[x] > $1 THEN RETURN p.translate_x[x], p.translate_y[x] END LOOP;`
[timestamp]);

【问题讨论】:

  • 请不要将表格定义发布为屏幕截图,edit 您的问题,并将相关表格的 CREATE TABLE 语句添加为 formatted text(与您使用 INSERT 语句的方式相同) )
  • 也向我们展示您的查询尝试,这很重要。

标签: arrays postgresql loops


【解决方案1】:

如果我理解正确,你可以这样做:

select * from (
    select i,id,layout_id,dining_table_id,x_position,y_position,translate_x[i],
           translate_y[i],start_timestamps[i],end_timestamps[i] from (
                          select generate_subscripts(translate_x,1) i,* from position
                  ) a
   ) b where start_timestamps<='2019-03-05 12:00:00'::timestamp 
            and end_timestamps>'2019-03-05 12:00:00'::timestamp

它应该可以工作,但是如果您可以更改数据库的定义,您应该创建一个新表,例如:

position_periods : (id_position integer ,start_timestamp timestamp,end_timestamp timestamp,translate_x integer,translate_y integer)

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 2016-07-02
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 2019-11-06
    相关资源
    最近更新 更多