内部连接后的SQL选择输出

问题描述 投票:-1回答:2

我有一个问题。我有2张桌子,我在人物ID上执行了inner join。现在,我要这些人的名字写出来。我试过了,但是它在第一个和第二个上写了first的名称。

SELECT g.id, g.idobject, 
       p.name || ' ' || z.last as Per1,
       p.name || ' ' || z.last as Per2
    FROM
        grup g 
           INNER JOIN people p on g.idper1=p.id 
           INNER JOIN people p on g.iper2=p.id
mysql sql output inner-join
2个回答
1
投票

您的代码应该失败。您需要不同的表别名:

SELECT g.id, g.idobject, 
       p1.name || ' ' || p1.last as Per1,
       p2.name || ' ' || p2.last as Per2
FROM grup g JOIN
     people p1 
     ON g.idper1 = p1.id JOIn
     people p2
     ON g.iper2 = p2.id;

如果您确实在使用MySQL,则适当的功能是CONCAT()或更好的功能CONCAT_WS()

SELECT g.id, g.idobject, 
       CONCAT_WS(' ', p1.name, p1.last) as Per1,
       CONCAT_WS(' ', p2.name, p2.last) as Per2
FROM grup g JOIN
     people p1 
     ON g.idper1 = p1.id JOIn
     people p2
     ON g.iper2 = p2.id;

1
投票

当两次连接同一张表时,使用不同的别名。

例如:

SELECT g.id, g.idobject, 
       concat(p1.name, ' ', p1.last) as Per1,
       concat(p2.name, ' ', p2.last) as Per2
    FROM
        grup g 
           INNER JOIN people p1 on g.idper1=p1.id 
           INNER JOIN people p2 on g.iper2=p2.id
© www.soinside.com 2019 - 2024. All rights reserved.