简体   繁体   中英

Selecting multiple timestamps between multiple start and end times from another table

So I have two tables:

+----------------+        +----------------------+
|data_raw        |        |label                 |
+----------------+        +----------------------+
|type (char)     |        |serial (bigint)       |
|time (timestamp)|        |start_time (timestamp)|
|data (bigint)   |        |end_time (timestamp)  |
|serial (bigint) |        |label (text)          |
|device (text)   |        +----------------------+
+----------------+

I need to get all rows in data_raw where the timestamp is between the start_time and end_time in all the rows of data_label and the serial is the same. I tried,

 SELECT time, data FROM data_raw WHERE time BETWEEN 
 (SELECT start_time FROM label) AND 
 (SELECT end_time FROM label);

but this wasn't working for me.

You can accomplish this by using a join. My postgre is rough, but I think this should do what you need:

SELECT time, data
FROM data_raw, label
WHERE data_raw.serial = label.serial 
AND time BETWEEN label.start_time AND label.end_time

I would suggest something like this. Are you looking for this information based on a specific label? If that's the case, That's where you'd swap out where I put 1.

WITH one_label AS (
SELECT * FROM label WHERE serial = 1)
SELECT time, data FROM data_raw 
WHERE time BETWEEN one_label.start_time AND one_label.end_time;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM