如何从具有自连接的子查询中获取数据?

qeeaahzv  于 2021-08-13  发布在  Java
关注(0)|答案(3)|浏览(352)

我的table:

friends(uid_1 int, uid_2 int)

我的问题是:

SELECT a.uid_1
     , a.uid_2 as a2
     , b.uid_1 as b1
     , b.uid_2
  from friend a 
  join friend b
    on a.uid_1 = b.uid_2;

我想从查询中获取a2和b1以作其他用途
所以现在这个查询:

Select a2,b1
from (SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
      from friend a join
           friend b
           on a.uid_1=b.uid_2
     )

不起作用。如何从一系列显示的数据中获取某些数据?

y53ybaqx

y53ybaqx1#

第一,你只是缺少一个别名为你的子查询如下-

Select a2,b1
from (
    SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
    from friend a join
    friend b
    on a.uid_1=b.uid_2
) A -- added A as a Alias

但是第二点,不确定您要对连接做什么,因为您的查询实现了连接条件,这与下面的查询是等价的-

SELECT * 
FROM friend 
WHERE uid_1 = uid_2
ttisahbt

ttisahbt2#

您需要子查询的表名别名,例如:select。。。从(子查询)t
然后可以使用完全限定名引用子查询内容

Select T.a2, T.b1
    from (SELECT a.uid_1,a.uid_2 as a2, b.uid_1 as b1, b.uid_2 b2
          from friend a join
               friend b
               on a.uid_1=b.uid_2
         ) T
k5ifujac

k5ifujac3#

你刚才不见了

Select a2,b1
from (SELECT a.uid_1,a.uid_2 as a2,b.uid_1 as b1,b.uid_2
  from friend a join
       friend b
       on a.uid_1=b.uid_2
 ) as temp -- here it is

相关问题