我有一个表(T1
),其中2列(X
和Y
)是id。这些对应的id
的名称位于另一个表格T2
)中,其中包含name
列。
假设我只使用X
,那么简单的内部联接就可以解决我在获取名称时的问题。
如
Select T1.somedata,T1.somedata1,T2.name from T1
Inner Join T2 ON T1.X=T2.id
但是,如果我想要为T1.Y
解析名称,该怎么办呢?name
内部加入会解决它吗?
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
以上查询错了,我知道。我可以使用name
获取与T1.X
和T1.Y
相对应的INNER Join
个内容吗?
-Beginner
答案 0 :(得分:5)
我建议始终在表和列中添加别名。因此,您将确定选择了哪些数据。
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
答案 1 :(得分:2)
这将选择两个名称作为单独的列:
Select T1.somedata,T1.somedata1,T2a.name, T2b.name
from T1
Inner Join T2 as T2a ON T1.X=T2a.id
Inner Join T2 as T2b ON T1.Y=T2b.id
以下内容将在结果集中生成两条记录:
Select T1.somedata, T1.somedata1, T2.name
from T1
Inner Join T2 ON T1.X=T2.id Or T1.Y=T2.id
答案 2 :(得分:1)
您需要两次加入表T2
并在名称上提供别名以避免歧义。
SELECT a.*,
b.name as NameB,
c.name as NameC
FROM T1 a
INNER JOIN T2 b
ON a.x = b.id
INNER JOIN T2 c
On a.y = c.id
答案 3 :(得分:0)
您需要连接表T2两次并在名称上提供别名以避免歧义。
SELECT a.*,
b.name as NameB,
c.name as NameC
FROM T1 a
INNER JOIN T2 b
ON a.x = b.id
INNER JOIN T2 c
On a.y = c.id