具有相同ID的2个表的内部联接 [英] Inner join of 2 tables with the same ID

查看:116
本文介绍了具有相同ID的2个表的内部联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表(T1),其中2列(XY)是id.这些对应的id的名称在另一个表(T2)中,该表的列为name.

I have a table(T1) in which 2 columns(X and Y) are id's. The name's of these corresponding id's are in another table (T2) with the column name.

假设我只是使用X,那么,简单的内部联接就可以解决我在获取名称时遇到的问题.

Suppose I was only using X then, a simple Inner join would have solved my problem in getting the name.

例如

Select T1.somedata,T1.somedata1,T2.name from T1
Inner Join T2 ON T1.X=T2.id

但是,如果我还想为T1.Y解析名称吗?内部联接会将哪个name解析为??

But,what if I want the name's to be resolved for the T1.Y also?, which name would the Inner Join resolve it to ??

Select T1.somedata,T1.somedata1,T2.name from T1
Inner Join T2 ON T1.X=T2.id
Inner Join T2 ON T1.Y=T2.id

我知道上述查询是错误的.我可以用INNER Join获得与T1.XT1.Y对应的那些name吗?

The above query is wrong, I know. Can I get the names of those corresponding to both T1.Xand T1.Y with an INNER Join?

-初学者

推荐答案

我建议始终为表和列添加别名.因此,您将确保选择了哪些数据.

I suggest always add aliases to tables and columns. So you will be sure which data are selected.

select
    T1.somedata,
    T1.somedata1,
    T2X.name as XName,
    T2Y.name as YName
from T1 as T1
    inner join T2 as T2X on T2X.id = T1.X
    inner join T2 as T2Y on T2Y.id = T1.Y

这篇关于具有相同ID的2个表的内部联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆