我正在为我的项目编写一个复杂的查询我有两个表,如下所示test,test_Av
测试:
CREATE table test(id int not null, title varchar(50), place
varchar(20), postcode varchar(20), primary key(id));
INSERT INTO test VALUES(1,'test','','91982');
INSERT INTO test VALUES(2,'test','','91982');
INSERT INTO test VALUES(3,'test','','91982');
INSERT INTO test VALUES(4,'test','','91982');
INSERT INTO test VALUES(5,'test','','91982');
Test_AV
CREATE table test_AV(id int not null, testid int, name varchar(25),
stringvalue varchar(25) ,primary key(id));
INSERT INTO test_AV VALUES(1,1,'latitude','16.15074');
INSERT INTO test_AV VALUES(2,1,'longitude', '-22.74426');
INSERT INTO test_AV VALUES(3,2,'latitude','16.13725');
INSERT INTO test_AV VALUES(4,2,'longitude', '-22.85822');
INSERT INTO test_AV VALUES(5,3,'latitude','14.85633');
INSERT INTO test_AV VALUES(6,3,'longitude', '-24.72379');
INSERT INTO test_AV VALUES(7,4,'latitude','14.86949');
INSERT INTO test_AV VALUES(8,4,'longitude', '-24.70150');
INSERT INTO test_AV VALUES(9,5,'latitude','15.03118');
INSERT INTO test_AV VALUES(10,5,'longitude', '-24.32523');
test_AV表中的testid是外键
我需要找到距离给定'纬度'和'经度'的半径100公里的结果来实现这一点我写了一些像这样的查询
select * from ( SELECT id,
title,
((ACOS(
SIN(16.15074 * 3.141592653 / 180)
* SIN((SELECT stringvalue from test_AV WHERE name='latitude')
* 3.141592653 / 180)
+ COS(16.15074 * 3.141592653 / 180)
* COS((SELECT stringvalue from test_AV WHERE name='latitude')
* 3.141592653 / 180)
* COS((-22.74426 - (SELECT stringvalue from test_AV WHERE name='longitude'))
* 3.141592653 /180))*6373)) AS distance FROM
test ) t where distance <= 100
在子查询的子查询位置我需要test_AV表中的所有纬度和经度值,当我写这个时,它说子查询说子查询返回多行
我该怎么做?
答案 0 :(得分:1)
正如wildplasser正确提到的那样,你需要将子查询与主查询相关联 - 请参阅下面的查询,注意子查询中的WHERE av.testid = ts.id
子句:
select * from ( SELECT id,
title,
((ACOS(
SIN(16.15074 * 3.141592653 / 180)
* SIN((SELECT stringvalue from test_AV av WHERE av.testid = ts.id and name='latitude')
* 3.141592653 / 180)
+ COS(16.15074 * 3.141592653 / 180)
* COS((SELECT stringvalue from test_AV av WHERE av.testid = ts.id and name='latitude')
* 3.141592653 / 180)
* COS((-22.74426 - (SELECT stringvalue from test_AV av WHERE av.testid = ts.id and name='longitude'))
* 3.141592653 /180))*6373)) AS distance FROM
test ts ) t where distance <= 100
那是为了修复您的查询。但是有一种将Oracle行转换为列的技术。您可以获取一个数据集,其中您的经度和纬度行与testid在一行中相关联:
select testid,
max(decode(name, 'longitude', to_number(stringvalue), NULL)) longitude,
max(decode(name, 'latitude', to_number(stringvalue), NULL)) latitude
from test_AV
group by testid
现在只需将此表加入test。