Note that there are some explanatory texts on larger screens.

plurals
  1. POEfficiently selecting from many-to-many relation in H2
    primarykey
    data
    text
    <p>I'm using H2, and I have a database of books (table Entries) and authors (table Persons), connected through a many-to-many relationship, itself stored in a table Authorship. The database is fairly large (900'000+ persons and 2.5M+ books).</p> <p>I'm trying to efficiently select the list of all books authored by at least one author whose name matches a pattern (LIKE '%pattern%'). The trick here is that the pattern should severly restrict the number of matching authors, and each author has a reasonably small number of associated books.</p> <p>I tried two queries:</p> <pre><code>SELECT p.*, e.title FROM (SELECT * FROM Persons WHERE name LIKE '%pattern%') AS p INNER JOIN Authorship AS au ON au.authorId = p.id INNER JOIN Entries AS e ON e.id = au.entryId; </code></pre> <p>and:</p> <pre><code>SELECT p.*, e.title FROM Persons AS p INNER JOIN Authorship AS au ON au.authorId = p.id INNER JOIN Entries AS e ON e.id = au.entryId WHERE p.name like '%pattern%'; </code></pre> <p>I expected the first one to be much faster, as I'm joining a much smaller (sub)table of authors, however they both take as long. So long in fact that I can manually decompose the query into three selects and find the result I want faster.</p> <p>When I try to EXPLAIN the queries, I observe that indeed they are very similar (a full join on the tables and only then a WHERE clause), so my question is: how can I achieve a fast select, that relies on the fact that the filter on authors should result in a much smaller join with the other two tables?</p> <p>Note that I tried the same queries with MySQL and got results in line with what I expected (selecting first is much faster).</p> <p>Thank you.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload