首页 > 解决方案 > SQL:组合两个表进行查询

问题描述

我想一次查询两个表,以找到给定他们名字的艺术家的键。问题是我的数据来自不同的来源,并且没有明确的标准来表示他们的名字(例如 Forename Surname vs. Surname, Forename),因此为此我有一个表格,其中包含在其余部分中使用的明确名称我的系统以及一个单独的别名表,以匹配每个艺术家的不同风格。

这是 PostgreSQL,但除了文本类型之外,它非常标准。如果您愿意,可以使用不同的替换字符:

create table Artists (
     id serial primary key,
     name text,
     -- other stuff not  relevant
);

create table Aliases (
     artist integer references Artists(id) not null,
     name text not null
);

现在我希望能够在单个查询中查询两组名称以获得适当的 id。有什么办法可以做到这一点?例如

select id from ??? where name = 'Bloggs, Joe';

我没有兴趣将我的模式关于“名称”的概念修改为更结构化的东西,例如单独的名字和姓氏,因为它不适合应用程序。我的大多数来源都没有结构化数据,有时一个或另一个名字是未知的,它可能是一个化名,或者有时“艺术家”可能是一个实体,如工作室。

标签: sql

解决方案


我想你想要:

select a.id
from artists a
where a.name = 'Bloggs, Joe' or
      exists (select 1
              from aliases aa
              where aa.artist = a.id and
                    aa.name = 'Bloggs, Joe'
             );

实际上,如果您只想要 id (而不是其他列),那么您可以使用:

select a.id
from artists a
where a.name = 'Bloggs, Joe'
union all   -- union if there could be duplicates
select aa.artist
from aliases aa
where aa.name = 'Bloggs, Joe';

推荐阅读