2015-05-07 60 views
1

我試圖連接3個不同的表,但難以遵循其他教程中的邏輯。如何使用SQL連接3個表(1查找)

table_1(user_ID, seller_country_ID) 
table_2(user_ID, users_country_ID) 
table_3(country_ID, country_Name) 

我想創建一個查詢,返回賣家國名和用戶國名。我可以使用加入來獲得賣家的國名,但是當涉及到獲取用戶國名時,我的邏輯能力就止步於此。我有一個WHERE子句進一步限制了返回的記錄,並且需要在那裏。

SELECT tbl1.user_ID, tbl1.seller_country_ID, tbl3.country_Name 
FROM table_1 AS tbl1 
JOIN table_3 AS tbl3 
ON tbl1.seller_country_ID = tbl3.country_ID 
WHERE <sales_type> = 1 

所以,我有表1和3,但不知道如何合併表2,以得到我的結果。

結果我要求是:

user ID, user_country, seller_country 
010101, USA, CANADA 

回答

3

你必須使用國家查找表seller_id加入和user_id說明separetly兩次,得到用戶和賣方國家

create table table_1(user_ID int, seller_country_ID int) 
create table table_2(user_ID int, users_country_ID int) 
create table table_3(country_ID int, country_Name varchar(50)) 


insert into table_1 values(1, 100) 
insert into table_1 values(2, 101) 

insert into table_2 values(1, 200) 
insert into table_2 values(2, 201) 


insert into table_3 values(100, 'USA') 
insert into table_3 values(101, 'China') 
insert into table_3 values(200, 'CANADA') 
insert into table_3 values(201, 'Japan') 

Select table_1.user_ID, uc.country_Name "User Contry", sc.country_Name "Seller Country" 
FROM table_1 INNER JOIN table_2 ON table_1.user_ID= table_2.user_ID 
INNER JOIN table_3 uc ON table_2.users_country_ID= uc.country_ID 
INNER JOIN table_3 sc ON table_1.seller_country_ID= sc.country_ID 

輸出

user_ID User Contry  Seller Country 
1  CANADA   USA 
2  Japan   China 

DEMO SQL FIDDLE

0

你可以做到這一點,在兩次加入TABLE_3。一旦獲得用戶國家和另一次獲得賣家國家。

SELECT 
    tbl1.user_id 
    , tbl3u.country_name 
    , tbl3s.country_name 
FROM 
    table_1 tbl1 
    JOIN table_2 tbl2 ON tbl1.user_id = tbl2.user_id 
    JOIN table_3 tbl3s ON tbl3s.country_ID = tbl1.seller_country_id 
    JOIN table_3 tbl3u ON tbl3u.country_id = tbl2.users_country_id 
WHERE <sales_type> = 1