2016-01-28 38 views
-1

我现在坐在一个问题上。我已经导入了一个开源的地理位置数据库。如何在只知道一个值的情况下从两个表中检索具有相同ID的多行

我有两个表我想要访问。

表A:
ID       | lat | lon
200 | 48 | 12

表B:
ID       |类型|价值
200 |城市      |慕尼黑
200 |状态|巴伐利亚

现在我想有这样的结果:
ID       | lat | lon | TypeValue | TypeValue
200 | 48 | 12     |慕尼黑                |巴伐利亚州

这是可能的只有一个查询?

编辑:我知道的唯一价值就是 “慕尼黑”

EDIT2:这是我到目前为止有:

SELECT 
geodb_coordinates.lat AS lat, 
geodb_coordinates.lon AS lon, 
geodb_textdata.text_val AS text 
FROM 
geodb_coordinates, 
geodb_textdata 
WHERE 
geodb_coordinates.loc_id = geodb_textdata.loc_id AND 
geodb_textdata.text_val LIKE :location 
GROUP BY geodb_textdata.text_val 
ORDER BY LENGTH(geodb_textdata.text_val) 
LIMIT 3 
+0

是的,它可以与自我加入。你试过什么了?表B中具有相同ID 2的记录数量是否可以更多,例如城市 - >州 - >国家 - >大陆? – Shadow

+0

你不能有两个同名的列... –

+0

@Shadow我现在得到的是,我可以有“ID | lat | TypeValue”。没有成功获取其他TypeValue。是的。表B可以具有更多具有相同ID的行。 –

回答

2

试着这么做:

Select A.ID,A.Iat, A.Ion, B.Value as TypeValue1, C.Value as TypeValue2 
from 
A inner join B on A.ID=B.ID and B.Type='City' 
Inner join B as C on B.ID=C.ID and C.Type='State' 
+0

应该是C.Type ='State'如果有超过2条记录(参见OP的评论),那么这个查询是不够的。 – Shadow

+0

@Shadow,是的,你是对的。 –

1

尝试像

SELECT b1.ID, a.lat, a.lon, b1.Value, b2.Value 
FROM table_b as b1 join table_a as a on a.ID=b1.ID, table_b as b2 
where b1.ID=b2.ID and b1.`Type`='City' and b2.`Type`='State' and b1.Value='Munich'; 

我想每个ID只有一个城市,对吧?

相关问题