sqlite查询:多选择联合

ljsrvy3e  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(317)

我有以下表格:
表格: table1 ```
id | timestamp | val
1 | 1577644027 | 0
2 | 1577644028 | 0
3 | 1577644029 | 1
4 | 1577644030 | 1
5 | 1577644031 | 2
6 | 1577644032 | 2
7 | 1577644033 | 3
8 | 1577644034 | 2
9 | 1577644035 | 1
10 | 1577644036 | 0
11 | 1577644037 | 1
12 | 1577644038 | 1
13 | 1577644039 | 1
14 | 1577644040 | 0

表格: `table2` ```
id | idFirst | idLast | val
1  |   3     |   9    |  0
2  |   11    |   13   |  13

我想执行一个查询,以编程方式获取引用的寄存器之间的时间戳差异 table2table1 其中的时间戳 idFirst 以及 idLast 在给定的时间戳之间( idFirst>firstInputTimestamp && idLast<lastInputTimestamp ).
也就是说,在 id =1个 table2 ,应该是 1577644035 以及 1577644029 ( 6 ). 如果是 id =2,差值为 1577644039-1577644037 ( 2 ).
我尝试的非工作方法如下:

SELECT timestamp2-timestamp1
(SELECT timestamp FROM table1 WHERE id IN (SELECT idFirst FROM table2) ORDER BY timestamp ASC) AS timestamp1,
(SELECT timestamp FROM table1 WHERE id IN (SELECT idLast FROM table2) ORDER BY timestamp ASC) AS timestamp2;
k97glaaz

k97glaaz1#

可以将第一个表与第二个表联接两次,每个id联接一次,然后取其差值:

SELECT
    t2.id,
    t1b.timestamp - t1a.timestamp AS difference,
    t2.val
FROM table2 t2
LEFT JOIN table1 t1a ON t2.idFirst = t1a.id
LEFT JOIN table1 t1b ON t2.idLast = t1b.id
ORDER BY
    t2.id;
6uxekuva

6uxekuva2#

我想绝对可以做到。

SELECT T2.id, abs(T11.timestamp - T12.timestamp)
FROM table2 T2
INNER JOIN table1 T11 ON T2.idFirst = T11.id
INNER JOIN table1 T12 ON T2.idSecond = T12.id

相关问题