从另一个表

时间:2016-02-19 19:31:42

标签: sql postgresql

所以我有两张桌子:

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

我需要获取data_raw中的所有行,其中time_amp在data_label的所有行中的start_time和end_time之间,并且序列是相同的。我试过了,

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

但这不适合我。

2 个答案:

答案 0 :(得分:0)

您可以使用联接来完成此操作。我的postgre很粗糙,但我认为这应该做你需要的:

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

答案 1 :(得分:0)

我会建议这样的事情。您是否根据特定标签查找此信息?如果是这样的话,那就是你换掉我放置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;