2
2
2g1c2021-08-10 10:33:21
PostgreSQL
2g1c, 2021-08-10 10:33:21

Postgresql, how to get rows of a table that fall within intervals recorded in a table with intervals?

i have table t. the values ​​in the t.sequence column are ordered and unique.
there is a table t_intervals with columns id - interval id, start and end - which point to t1.sequence.

i can get data from t for 1 interval like this:

WITH interval AS(
  SELECT start, end from t_intervals 
  WHERE id=10
  )
SELECT * FROM t
WHERE sequence BETWEEN (select start from interval) 
  AND (select end FROM interval);


but I would like to receive data for several intervals and for a known number of them I can do this:
WITH interval1 AS(
  SELECT start, end from t_intervals 
  WHERE id=10
  ),
  interval2 AS(
  SELECT start, end from t_intervals 
  WHERE id=20
  )
SELECT * FROM t WHERE 
  WHERE sequence BETWEEN (select start from interval1) 
    AND (select end FROM interval1)
  OR sequence BETWEEN (select start from interval2) 
    AND (select end FROM interval2);

but i can filter t_intervals by different rules and i can't know how many intervals will fall under them, so i would like to have something like this:
WITH intervals AS(
  SELECT start, end from t_intervals
  WHERE id in (2,10,30, ..., n)
  )
SELECT * FROM t 
WHERE OR_ROWS(
  sequence BETWEEN (select start from intervals)
  AND (select end FROM intervals)
);


where OR_ROWS will generate a condition:
sequence BETWEEN (select start from intervals) AND (select end FROM intervals)

for each line.

how to do something similar? Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Akina, 2021-08-10
@2g1c

A complete feeling that something like

SELECT [DISTINCT] t.*
FROM t
JOIN t_intervals ti ON t.sequence BETWEEN ti.start AND ti.end
WHERE ti.id in (2,10,30, ..., n)

If the intervals in t_intervals are guaranteed not to intersect (although I personally don't know how to organize it in the form of constraints, and the trigger logic doesn't), then DISTINCT is not required.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question