[英]SQL JOIN to get the compare two values/row from table “A” and the same row from table “B”
I have two tables with the following rows我有两个包含以下行的表
Table A (transaction)表 A(事务)
Order Seller Customer
1 300 500
Table B (Persons)表 B(人)
PersonID FullName
300 Peter White
500 Scott Bold
I want a result like this我想要这样的结果
Order Seller Customer FullName (Seller) FullName (customer)
1 300 500 Peter White Scott Bold
I've tried multiple things however which makes more sense is a join a table twice, however I'm getting:我尝试了多种方法,但是更有意义的是两次加入表,但是我得到了:
Ambiguous column name不明确的列名
This is SQL Server 2019.这是 SQL 服务器 2019。
Basically I'm looking to retrieve info from the same table instead of creating additional tables.基本上我希望从同一个表中检索信息,而不是创建其他表。 Is that possible?那可能吗? If yes, how do you do?如果是,你会怎么做? Thank you in advance.先感谢您。
As @jarlh wrote in comment:正如@jarlh 在评论中所写:
select t.order, t.seller, t.customer, sel.fullname, cust.fullname
from transaction t
join persons sel -- sel is an alias to persons table
on sel.personid = t.seller
join persons cust
on cust.personid = t.customer;
Query with join
will return the result as long as both seller and customer exist in persons
table -- here it should as source table names transactions
:).只要卖家和客户都存在于persons
表中,使用join
查询就会返回结果——这里它应该作为源表名transactions
:)。
I have another form of query it still join table B twice.我有另一种形式的查询,它仍然加入表 B 两次。
This is archaic syntax which I don't recommend but for beginner know the concept of JOIN:这是我不推荐的古老语法,但初学者知道 JOIN 的概念:
select t.*,B.FullName as FullName (customer) from
(
select A.Order,A.Seller,A.Customer,B.FullName as FullName(Seller)
from A,B where A.Seller=B.PersionID
) t, B where t.Customer=B.PersionID
The proper way of JOIN: JOIN的正确方式:
select t.*,B.FullName as FullName (customer) from
(
select A.Order,A.Seller,A.Customer,B.FullName as FullName(Seller)
from A JOIN B ON A.Seller=B.PersionID
) t JOIN B ON t.Customer=B.PersionID
Hoping this can help you.希望这可以帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.