简体   繁体   中英

mysql select from multiple tables where two items match

What would be the best way to select data from one table and match it to the data in another then return those both together?

I have a table with a bunch of info in it and it's relevant country name. I need to get from another table the country code that matches the name of the country

Would it be best to use say a mysql JOIN function to link the data together or use something like a foreach() to make separate requests to get each item.

I have a feeling JOIN (or something similar) would be the best solution, however I don't really know how to construct the mySQL query bearing in mind I need data returned from both table.

$sql = "SELECT DISTINCT r.country,c.* FROM resorts LEFT JOIN ( SELECT * FROM Country WHERE r.country = c.countryName )";

Table 1

  • country

Table 2

  • id
  • countryName
  • countryCode

This is a very simple concept in MySQL; one of the simplest joins:

SELECT columns, countryCode
FROM t1
JOIN t2 ON (t1.countryName = t2.countryName)

EDIT: You added your real table names/columns in your question, so I'll rewrite the query with those:

SELECT id, countryName, countryCode
FROM Country
JOIN resorts ON (country = countryName)
SELECT r.country,c.id, c.CountryName, c.CountryCode
FROM resorts as r
LEFT JOIN Country AS c 
  ON r.country = c.countryName

Or get rid of the LEFT to return all resort records that have a country (as opposed to the LEFT which returns all resort records, regardless if a country record exists

The Join in SQL does return data from both tables, when you join 2 tables, the SQL parser/engine makes a "Cartesian product" and loop on each row from table1 and check the join condition with each row from second table table2 returning the selected columns from both tables. So, eg at the end when you join table1 ( which contains 2 rows) with table2 ( which contains 3 rows ) you actually do checks/loops of 2*3 which is 6.

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