繁体   English   中英

MYSQL SELECT WHERE子句:如何包含另一个表中的列?

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

在MYSQL中,假设我有以下两个表。

“轮廓”:

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

“国家”:

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

"profile"表的角度进行查询时,如下所示:

WHERE fullname = 'Cindy'

然后在结果中,我如何从另一个表中包含一列(以获取如下所示的结果):

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

您可以使用

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'

您需要加入表。 例如:

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";

您应该使用JOIN

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

有关更多信息,请检查: http : //www.w3schools.com/sql/sql_join_inner.asp

尝试这个..

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'

您需要使用个人资料和国家/地区表之间的联接,如下所示

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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