使用sqlite命令连接2个表

时间:2017-05-22 05:59:35

标签: sqlite join

我创建了一个名为sample.db的数据库。

我导入了2个csv文件-test和test1(数据库中的表)

我想基于3列加入两个表 - 时间戳,经度和纬度。

测试

o3,pm,co,so2,no2,longitude,latitude,timestamp     
61,82,52,49,54,10.2466,56.2091,1410693900    
66,83,51,44,51,10.2466,56.2091,1410694200    
68,80,54,41,56,10.2466,56.2091,1410694500    
66,79,53,42,59,10.2466,56.2091,1410694800    
71,75,57,45,61,10.2466,56.2091,1410695100    
75,75,60,50,61,10.2466,56.2091,1410695400   
122,97,172,40,53,10.2507,56.2026,1412101200

TEST1

status,avgMeasuredTime,avgSpeed,extID,medianMeasuredTime,TIMESTAMP,vehicleCount,_id,REPORT_ID,Lat1,Long1,Lat2,Long2,Distance between 2 points,duration of measurements,ndt in kmh    
OK,61,60,668,61,1410693900,4,20746723,158324,56.2091,10.2466,56.2258,10.1166,1030,52,71
OK,61,60,668,61,1410694200,1,20747172,158324,56.2091,10.2466,56.2258,10.1166,1030,52,71
OK,63,58,668,63,1410694500,3,20747545,158324,56.2091,10.2466,56.2258,10.1166,1030,52,71
OK,71,52,668,71,1410694800,6,20747994,158324,56.2091,10.2466,56.2258,10.1166,1030,52,71
OK,67,55,668,67,1410695100,5,20748443,158324,56.2317,10.1050,56.2091,10.2466,1030,52,71
OK,62,59,668,62,1410695400,6,20748892,158324,56.2317,10.1050,56.2091,10.2466,1030,52,71
OK,67,55,668,67,1412101200,13,20749341,158324,56.2317,10.1050,56.2026,10.2507,1030,52,71

预期输出

ozone,particullate_matter,carbon_monoxide,sulfure_dioxide,nitrogen_dioxide,longitude,latitude,timestamp,avgMeasuredTime,avgSpeed,medianMeasuredTime,Distance between 2 points,duration of measurements,ndt in kmh
61,82,52,49,54,10.2466,56.2091,1410693900,61,60,61,1030,52,71
66,83,51,44,51,10.2466,56.2091,1410694200,61,60,61,1030,52,71
68,80,54,41,56,10.2466,56.2091,1410694500,63,58,63,1030,52,71
66,79,53,42,59,10.2466,56.2091,1410694800,71,52,71,1030,52,71
71,75,57,45,61,10.2466,56.2091,1410695100,67,55,67,1030,52,71
75,75,60,50,61,10.2466,56.2091,1410695400,62,59,62,1030,52,71
122,97,172,40,53,10.2507,56.2026,1412101200,67,55,67,1030,52,71

如您所见,我想根据时间戳,经度和纬度加入。 table2(test1)中有两个经度值。所以我想比较table1中与table2中任何经度值匹配的经度。同样的纬度。

我尝试了什么

select * 
from test 
join test1 
    on test.timestamp=test1.TIMESTAMP and
    test.longitude=test1.Long1 or 
    test.longitude=test1.Long2 and 
    test.latitude=test1.Lat1 or 
    test.latitude=test1.Lat2;

此外,我想将结果存储在新表中。

我是sqlite的新手。所以请帮助:))

2 个答案:

答案 0 :(得分:1)

使用括号对条件进行分组。您需要时间戳匹配的行AND(纬度/长度对1匹配或纬度/长度对2匹配)

select * 
from test 
join test1 
    on test.timestamp = test1.TIMESTAMP and
    ((test.longitude = test1.Long1 and test.latitude = test1.Lat1) or
     (test.longitude = test1.Long2 and test.latitude = test1.Lat2));

答案 1 :(得分:-1)

INNER JOIN的SQL命令:

SELECT latitude
FROM test
INNER JOIN test1 ON test.latitude = test1.latitude;

重复其他列。