简体   繁体   中英

Trying to JOIN columns from two different tables

I have one table (city_data) with the columns 'year', 'city_name' and 'avg_temp'. The other table is global_data and has the columns 'avg_temp' and 'year'. I am trying to create a table which has the average temperature of London, the global average temperature for all the years. My SQL code is the following:

SELECT city_data.avg_temp, city_data.year
FROM city_data
JOIN global_data
ON city_data.year = global_data.avg_temp
WHERE city= 'Paris'

I get no error but cannot get the expected result. I think I am not able to understand what I need to put in the ON clause.

FROM city_data
JOIN global_data
ON city_data.year = global_data.year

-- it should be global_data.year in Join

WHERE city= 'Paris'

This is completely based on the partial understanding

SELECT city_name, AVG(city_data.avg_temp) as global_avg
    FROM
    city_data
    JOIN global_data
    ON city_data.year = global_data.year
    WHERE city_name = 'Paris'
    GROUP BY city_data.city_name

As year is the only common attribute, join using it. Then fetch the city average table as it is readily availble in the city_data . Lastly do the avg for global_data , as you want to fetch it across years.

SELECT `city_name`, `city_data`.`avg_temp` AS city_avg_temp, AVG(`global_data`.`avg_temp`) AS global_avg_temp
    FROM `city_data`
    JOIN `global_data` 
        ON `city_data`.`year` = `global_data`.`year`
    WHERE `city_name` = 'London'
    GROUP BY `city_data`.`city_name`

I suppose that the table global_data has one row per year, while city_data has one row per year and city. This means you can simply join the two on the year they have in common:

select year, g.avg_temp as global_average, c.avg_temp as paris_average
from global_data g
join city_data c using (year)
where c.city = 'Paris'
order by year;

If you don't like to join the two and only then mention Paris, you can also turn this into:

select year, g.avg_temp as global_average, p.avg_temp as paris_average
from global_data g
join (select * from city_data where city = 'Paris') p using (year)
order by year;

As of MySQL 8 you can even use a WITH clause to "prepare" Paris:-)

with paris as (select * from city_data where city = 'Paris')
select year, g.avg_temp as global_average, paris.avg_temp as paris_average
from global_data g
join paris using (year)
order by year;

Or consider Paris a join criteria:

select g.year, g.avg_temp as global_average, p.avg_temp as paris_average
from global_data g
join city_data p on p.year = g.year and p.city = 'Paris'
order by g.year;

As you see, there are many ways to write the same query and the DBMS would probably come up with the same execution plan for all. So, just pick the query you like best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM