我有两张桌子。第一个有一系列数据,有三列[z,s,c]称之为tblbaseline。第二个表具有相同的结构[z,s,c]称之为tbldatalog。我想在tblbaseline中找到使用列s匹配tbldatalog的记录,它们与tbldatalog中的记录类似但不一定相同。我可以根据列s提取所有匹配的记录,但是如果我希望tblbaseline中的任何记录是tbldatalog中相应记录的加或减5,我如何另外过滤列c。
此代码为我提供了基于列s和c的所有匹配记录:
select baseline.count from baseline LEFT JOIN data_log where baseline.sample=data_log.sample AND baseline.count=data_log.count;
此代码不起作用...
select baseline.count from baseline LEFT JOIN data_log where baseline.sample=data_log.sample AND baseline.count>= data_log.count -3 OR baseline.count<= data_log.count +3;
这是表结构:
CREATE TABLE baseline (id INTEGER PRIMARY KEY, zone INTEGER, sample INTEGER, count INTEGER, sqlTimeStamp DATETIME DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE data_log (id INTEGER PRIMARY KEY, zone INTEGER, sample INTEGER, count INTEGER, sqlTimeStamp DATETIME DEFAULT CURRENT_TIMESTAMP);
以下是表格数据:
sqlite> select * from baseline;
1 | 2 | 1 | 186 | 2015-07-24 16:31:38 2 | 2 | 2 | 183 | 2015-07-24 16:31:47 3 | 2 | 3 | 170 | 2015-07-24 16:32:01 4 | 2 | 4 | 165 | 2015-07-24 16:32:12 5 | 5 | 1 | 115 | 2015-07-24 16:32:26 7 | 5 | 2 | 113 | 2015-07-24 16:33:12 8 | 5 | 3 | 111 | 2015-07-24 16:33:23 9 | 5 | 4 | 109 | 2015-07-24 16:33:33
sqlite> select * from data_log;
1 | 0 | 1 | 115 | 2015-07-24 16:34:09 2 | 0 | 2 | 113 | 2015-07-24 16:34:18 3 | 0 | 3 | 111 | 2015-07-24 16:34:28 4 | 0 | 4 | 109 | 2015-07-24 16:34:42
以下查询和结果:
sqlite> select baseline.count from baseline LEFT JOIN data_log where baseline.sample=data_log.sample AND baseline.count=data_log.count;
115 113 111 109
sqlite> select baseline.count from baseline LEFT JOIN data_log where baseline.sample=data_log.sample AND baseline.count between data_log.count+60 AND data_log.count-60;
带有+/- 60条件的查询应该返回记录5-9并另外记录4个基线表。
答案 0 :(得分:0)
LEFT JOIN只在ON子句中使用一个连接条件。
如documentation所示,AND的优先级高于OR,因此您的查询与以下内容相同:
select baseline.count
from baseline
LEFT JOIN data_log
where ( baseline.sample = data_log.sample
AND baseline.count >= data_log.count - 3)
OR baseline.count <= data_log.count + 3;
您应该插入正确的括号:
select baseline.count
from baseline
LEFT JOIN data_log
ON baseline.sample = data_log.sample
AND (baseline.count >= data_log.count - 3 OR
baseline.count <= data_log.count + 3 );
或只是使用BETWEEN:
SELECT baseline.count
FROM baseline
LEFT JOIN data_log
ON baseline.sample = data_log.sample AND
baseline.count BETWEEN data_log.count - 3 AND data_log.count + 3;