【问题标题】:SQL Join table from 1 of 2 different tables optimized search来自 2 个不同表中的 1 个的 SQL 连接表优化搜索
【发布时间】:2017-04-18 16:37:52
【问题描述】:

为了简化,我有四个表,书、出版商、作者和公司。书籍和出版商都对作者有引用,但该引用可以为空

我可以通过像这样使用 OR 连接查询连接作者表来找到作者,但速度非常慢。

edit 我必须使用作者表来加入另一个。

架构:

select book.title, author.name, company.name as company_name from book inner join publisher on book.publisher_id = publisher.id inner join author on (book.author_id = author.id OR publisher.author_id = author.id) inner join company on author.company_id = company.id;

我想知道优化此查询的最佳方法是什么,而不是加入 OR 条件。谢谢

【问题讨论】:

  • 请在问题中添加您的表格结构(作为文本)

标签: sql postgresql join query-optimization


【解决方案1】:

你是对的。 ON 子句中的 OR 确实会减慢查询速度。

改为使用两个left joins:

select b.title, coalesce(ab.name, ap.name) as name
from book b inner join
     publisher p
     on b.publisher_id = p.id left join
     author ab
     on b.author_id = ab.id left join
     author ap
     on p.author_id = ap.id;

正式地,如果您只想返回在其中一个表中匹配的行,则可能需要添加 where ab.id is not null or ap.id is not null

【讨论】:

  • 感谢您的回复,我更新了问题,因为我必须实际使用该作者表来加入另一个表
猜你喜欢
  • 2022-11-20
  • 2016-12-10
  • 1970-01-01
  • 2013-07-04
  • 1970-01-01
  • 2021-11-02
  • 2013-11-11
  • 1970-01-01
  • 2017-04-22
相关资源
最近更新 更多