加入两个表,不加入任何外键和不同的无关ID

时间:2015-05-15 14:19:12

标签: sql postgresql join

我有两张桌子。

CompanyNames:
company_name text (Unique)
companyname_id bigint 

HomeNickNames:
home_nickname text (Unique)
nickname_id bigint

因此,行将如下:

    CompanyNames
    ==============
    company_name   ||   companyname_id
|:--------------------------------------:|
     Robert         |      123
     Mr.Robert      |      123
     Mr.RobertGrant |      123



    HomeNiceNames
    ==============
    home_nickname  ||   nickname_id
|:-------------------------------------:|
     Robert         |      431
     Robb           |      431
     DearRobb       |      431

假设几乎所有公司名称和昵称都可以加入,因为公司名称和昵称相同。

我需要一个可以生成以下结果的查询:

       name_id || home_nickname
|:-----------------------------------:|
       123     |   Robb
       123     |   Robert
       123     |   DearRobb 

2 个答案:

答案 0 :(得分:2)

首先找到Robert,然后使用该ID找到所有缺口:

select 
   c.companyname_id
  ,n2.home_nickname
from CompanyNames as c
join HomeNiceNames as n
  on c.company_name = n.home_nickname -- match Robert
join HomeNiceNames as n2
  on n.nickname_id = n2.nickname_id   -- match nickname with same id as Robert

答案 1 :(得分:1)

仍然不确定你在寻找什么。但只是我的猜测:

http://sqlfiddle.com/#!9/a2f0a/2

SELECT t.companyname_id, t2.home_nickname
FROM (SELECT companyname_id, GROUP_CONCAT(company_name) names
FROM CompanyNames
GROUP BY companyname_id) t
LEFT JOIN HomeNiceNames
ON FIND_IN_SET(HomeNiceNames.home_nickname, t.names)
LEFT JOIN HomeNiceNames t2
ON HomeNiceNames.nickname_id = t2.nickname_id