具有相同ID的2个表的内部联接

时间:2012-10-26 07:01:08

标签: mysql sql join inner-join

我有一个表(T1),其中2列(XY)是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.XT1.Y相对应的INNER Join个内容吗?

-Beginner

4 个答案:

答案 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