2017-04-18 80 views
0

作为简化,我有四个表格,书籍,出版商,作者和公司。图书和出版商均有作者参考,,但该参考文献可为空SQL从2个不同的表格中选择1个进行优化搜索

我可以通过使用这样的OR连接查询加入作者表来找到作者,但它非常慢。我不得不使用作者表来加入另一个。

模式:

schema design

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条件。谢谢

+0

请在问题 –

回答

0

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

相反,使用两个left join S:

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如果你只是想在一个表用一根火柴返回行。

+0

中添加您的表结构(作为文本)感谢您的回复,我更新了问题,因为我必须实际使用该作者表来加入另一个表 –

相关问题