2017-04-18 84 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

中添加您的表結構(作爲文本)感謝您的回覆,我更新了問題,因爲我必須實際使用該作者表來加入另一個表 –

相關問題