简体   繁体   中英

MYSQL SELECT WHERE Clause : How to include a column from another table?

In MYSQL, let's say I have following two tables.

"profile":

fullname | gender | country_code
-----------------------------------
Alex     | M      | us
Benny    | M      | fr
Cindy    | F      | uk

"country":

country_code | country_name
-----------------------------
jp           | Japan
us           | United States of America
fr           | France
sg           | Singapore
uk           | United Kingdom

While querying from "profile" table's perspective, like this:

WHERE fullname = 'Cindy'

Then in the result, how do i include a column from another Table (to get the results like this below):

fullname | gender | country_code | country_name
------------------------------------------------
Cindy    | F      | uk           | United Kingdom

You can use

select a.fullname, a.gender, b.country_code, b.country_name 
FROM profile a 
LEFT JOIN country b ON a.country_code = b.country_code 
WHERE a.fullname='Cindy'

You need to JOIN the tables. For example:

select a.fullname, a.gender, b.country_code, b.country_name 
  from profile a JOIN country b 
    on a.country_code = b.country_code 
 where a.fullname='Cindy'

请尝试以下操作:

Select * from profile natural join country where fullname='Cindy'
 select fullname, gender, profile.country_code as country_code, country_name from profile join country on profile. country_code = profile.country_code where fullname = "Cindy";

You should use JOIN :

SELECT profile.*, country.country_name
FROM Customers
INNER JOIN Orders
ON profile.country_code=country.country_code

For more info check this : http://www.w3schools.com/sql/sql_join_inner.asp

Try this..

SELECT t1.fullname, t1.gender t1.country_code,t2.country_name
FROM profile AS t1 INNER JOIN country AS t2 ON t1.country_code = t2.country_code where t1.fullname='cindy';
select p.fullname,p.gender,p.country_code,c.country_name from profile p 
INNER JOIN country c on p.country_code=c.country_code where p.fullname='Cindy'

You need to use join between profile and country table as below

SELECT
profile.fullname,
profile.gender, 
country .country_code, 
country .country_name 
FROM profile as profile JOIN country as country 
       ON (profile.country_code = country.country_code)
  WHERE profile.fullname = 'Cindy'

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