我有两张桌子:
TABLE:城市
city_id, lat, lon, name, country_id
TABLE:国家
country_id, name
我想要一个返回的SQL查询:
cities.lat, cities.lon, cities.name, countries.name(for the corresponding cities.country_id)
我发誓这一定很容易。但我无法让它发挥作用。
答案 0 :(得分:1)
您可以使用连接。也总是使用表名的别名来理解简单和标准的规则。
select
ci.lat, ci.lon, ci.name, cn.name
from
city ci
inner join
countries cn on ci.country_id = cn.country_id
答案 1 :(得分:0)
如果我明白了,那就是查询。
SELECT cities.lat, cities.lon, cities.name, countries.name
FROM cities INNER JOIN countries
ON cities.country_id = countries.country_id
顺便说一下,从cities.country_id
引用countries.country_id
的名称可以看出,您应该明确说明。
答案 2 :(得分:0)
这就是我使用子查询解决它的方法。但是使用上面的Ajay2707和marc_s给出的答案。它产生相同的结果。我把我的答案仅供参考(子查询):)
SELECT cities.name AS city, cities.lon, cities.lat, (SELECT countries.name AS country FROM countries WHERE countries.country_id=cities.country_id ) AS country FROM cities
答案 3 :(得分:-1)
SELECT
ct.name, ct.lat, ct.lon, cnt.name
FROM
cities ct, countries cnt
WHERE
ct.country_id = cnt.country_id
[Using Join Keyword]
SELECT ct.name, ct.lat, ct.lon, cnt.name
FROM cities ct
INNER JOIN countries cnt
ON ct.country_id = cnt.country_id;
答案 4 :(得分:-2)
select
a.name, a.country_id, b.cities, b.city_id, b.lat, b.lon, b.name
from
cities b, countries a
where
b.country_id = a.country_id