簡體   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