简体   繁体   中英

How do I combine results from more than one table?

I have to tables: cities and clients

cities: cities_id, cities_name

  1. New York
  2. Amsterdam
  3. Paris
  4. Milan
  5. etc.

Clients: columns with personal informaition but the following two columns are importen: plac_of_residence_id and place_of_birth_id. These two columns contain the different value from cities. For example:

  1. client_id: 1
  2. client_name: John
  3. client_sex: m
  4. plac_of_residence_id: 3 (cities_id)
  5. place_of_birth_id: 1 (cities_id)

How do I get two different values from table cities?

My sql statement is as follows:

SELECT * FROM clients C LEFT JOIN cities C ON C.plac_of_residence_id = C.cities_id AND place_of_birth_id = C.cities_id WHERE C.client_id = $client_id";

I get same citiesname for plac_of_residence_id as for place_of_birth_id instead of two different cities

How can i get as output: Paris and New York?

You should join cities two times

"SELECT C.*, a.*, b.* FROM clients C 
LEFT JOIN cities a ON C.plac_of_residence_id = a.cities_id 
LEFT JOIN cities b on  c.place_of_birth_id = b.cities_id 
WHERE C.client_id = $client_id";

Instead of using an AND in your statement you have to use an OR:

SELECT * FROM clients C LEFT JOIN cities C ON C.plac_of_residence_id = C.cities_id OR place_of_birth_id = C.cities_id WHERE C.client_id = $client_id";

This is because you want to have both: city of birth and the current residence. With your example above:

For John the join requirement (your "ON" part) should evaluate to true iff current row in cities table is no. 3 OR no. 1 because John is in a relationship to both entries.

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