我想知道如何在下面的例子中使用同一个表的2个实例,我知道该怎么做但我不能让它适用于我的任务。
我有以下表格:
任务:找出两个不同代理商提供的空间的地址,代理商名称1,代理商名称2(两个代理商的组合是唯一的)。
我尝试了什么:
1)
SELECT ADDRESS,A.NAME,B.NAME
FROM AGENCY A
INNER JOIN OFFER O ON A.ID_AGENCY=O.ID_AGENCY
INNER JOIN SPACE S ON O.ID_SPACE=S.ID_SPACE
WHERE S.ID_SPACE=ANY(SELECT S.ID_SPACE FROM AGENCY B
INNER JOIN OFFER O ON B.ID_AGENCY=O.ID_AGENCY
INNER JOIN SPACE S ON O.ID_SPACE=S.ID_SPACE
);
2)
SELECT ADDRESS
FROM AGENCY A
INNER JOIN OFFER O ON A.ID_AGENCY=O.ID_AGENCY
INNER JOIN SPACE S ON O.ID_SPACE=S.ID_SPACE
INTERSECT
SELECT ADDRESS
FROM AGENCY B
INNER JOIN OFFER O ON B.ID_AGENCY=O.ID_AGENCY
INNER JOIN SPACE S ON O.ID_SPACE=S.ID_SPACE
WHERE A.ID_AGENCY<>B.ID_AGENCY;
在第二个例子中,我不知道如何让它显示A.name和b.name,因为如果我尝试添加它们,则相互作用不会起作用......
我试着在最后3个小时内做到这一点,遗憾的是,我想我不能用迄今为止的技能做到这一点。 :(
提前致谢
编辑1:我希望你理解,那应该是什么样的。
机构
id_agency name
---------- -------
1 Agency1
2 Agency2
3 Agency3
空间
id_space address
--------- --------
1 address1
2 address2
3 address3
优惠
id_agency id_space
----------- --------
1 1
2 1
3 2
预期产出:
Address Name1 Name2
----------- -------- -------
address1 Agency1 Agency2
答案 0 :(得分:2)
要将结果分为1行,每行代理每行,如您所要求的那样:
select S.address as address, A1.name as agency_1, A2.name as agency_2
from offer O1
join offer O2
on O2.id_space = O1.id_space
and O2.id_agency != O1.id_agency
join space S
on S.id_space = O1.id_space
join agency A1
on A1.id_agency = O1.id_agency
join agency A2
on A2.id_agency = O2.id_agency
;
&#34;核心功能&#34;这里是offer
no.1(O1
别名)与offer
no.2(O2
别名)关于id_space
相等的联接,但{的差异{1}}。
一项有趣的练习:要将结果分成多行,每行一个代理商:
id_agency