首页 > 解决方案 > SQLite 关系表

问题描述

有一个 SQLite 数据库,每隔几秒就会存储 28 个值。我遇到的问题是该值存储在与存储变量名的表不同的表中。现在,如果可能的话,我想将值导出到例如 Excel,因此需要查询两个表。每次存储值时,值的 id 都会增加,因此需要有一个查询来读取特定变量的每个 id。但是我的 SQL 知识还不够好,所以希望我能在这里得到一些帮助。

数据库是这样建立的: 表 1(称为记录)

id  valueid  variable
1   1        foo
2   3        bar
3   4        foobar
4   5        foo
5   6        bar
...

表2(调用值)

id  value
1   3.14
3   42
4   123
5   3.1415
6   4242
...

因此,如果我想读出所有 foo,它会将值存储在 value-table 中,id 为 1、4 等(有时 valueid 会增加 2 而不是 1)。是否可以使用类似的 SQL 命令SELECT all value FROM (table) value WHERE record.variable = foo

标签: sqlite

解决方案


您可以在第一个表的 valueid 列上连接两个表,并使用 Where 将其过滤为仅表 1 中值为 foo 的记录,如下所示:

--Select all columns from t2 (value table)
--Join the value table on table 1 using the foreign key column valueid of
--table 1, which is the relationship to the id column of value table
--Using INNER JOIN will only return results where a match is found in value table
--Use the WHERE clause to filter down to only records from table 1 with variable = 'foo'
--You can use AND to add to the conditions of your WHERE clause to filter by date range

SELECT t2.*
FROM record AS t1
INNER JOIN value AS t2
ON t2.[id] = t1.[valueid]
WHERE t1.[variable] = 'foo' AND t2.[TimeStamp] >= someTimeStamp AND t2.[TimeStamp] <= someOtherTimeStamp

推荐阅读