[英]How to join 3 tables (1 lookup) with SQL
I am trying to join 3 different tables but having difficulty following the logic in other tutorials. 我正在尝试加入3个不同的表,但很难遵循其他教程中的逻辑。
table_1(user_ID, seller_country_ID)
table_2(user_ID, users_country_ID)
table_3(country_ID, country_Name)
I am trying to create a query that returns sellers country name and the users country name. 我正在尝试创建一个返回卖家国家/地区名称和用户国家/地区名称的查询。 I can use a join to get the sellers country name, but my logic abilities stop there when it comes to getting the users country name.
我可以使用联接来获取卖家的国家/地区名称,但在获取用户国家/地区名称时,我的逻辑能力就会停止。 I have a WHERE clause that further restricts the records returned and that needs to be there.
我有一个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
So, I've got tables 1 and 3, but not sure how to incorporate table 2 to get my results. 所以,我有表1和表3,但不知道如何结合表2来获得我的结果。
Results I am seeking are: 我想要的结果是:
user ID, user_country, seller_country
010101, USA, CANADA
You have to use country look up table join with seller_id and user_id separetly two times, to get user and seller country 您必须使用country_id和country_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
OUTPUT OUTPUT
user_ID User Contry Seller Country
1 CANADA USA
2 Japan China
You could do this and join table_3 in twice. 你可以这样做并加入table_3两次。 Once to get users country and another time to get sellers country.
一旦获得用户国家和另一个时间来获得卖家国家。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.