sql - 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';
我没有兴趣将我的模式关于“名称”的概念修改为更结构化的东西,例如单独的名字和姓氏,因为它不适合应用程序。我的大多数来源都没有结构化数据,有时一个或另一个名字是未知的,它可能是一个化名,或者有时“艺术家”可能是一个实体,如工作室。
解决方案
我想你想要:
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';
推荐阅读
- r - R blastula 的 send_stmp 给出“邮件失败:451”
- django - 从数据库(postgresql)导入的数据在 django 管理面板中出现两次
- reactjs - 带有 React Native 和 Expo 的 3DS2 BrowserInfo 数据
- php - 致命错误:未捕获的错误:调用 /public_html/wp-includes/error-protection.php:119 中未定义的函数 apply_filters()
- sql - 结合多个联合查询 - 这是最好的方法吗?
- arrays - 如何对 UIImages 数组进行排序?
- python - Selenium 不会返回所需的所有元素
- python - 将输出从循环保存到不同的数据框,然后保存到 excel
- asp.net - ASP.NET 核心策略检查中缺少“aud”声明会阻止授权,但它在 id 令牌中
- linux - 关于 Linux shell 上的脚本执行权限