Skip to content
Advertisement

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:

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.

Advertisement

Answer

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:

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

As of MySQL 8 you can even use a WITH clause to “prepare” Paris 🙂

Or consider Paris a join criteria:

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement