Note that there are some explanatory texts on larger screens.

plurals
  1. POSQL: find entries in 1:n relation that don't comply with condition spanning multiple rows
    primarykey
    data
    text
    <p>I'm trying to optimize SQL queries in Akonadi and came across the following problem that is apparently not easy to solve with SQL, at least for me:</p> <p>Assume the following table structure (should work in SQLite, PostgreSQL, MySQL):</p> <pre><code>CREATE TABLE a ( a_id INT PRIMARY KEY ); INSERT INTO a (a_id) VALUES (1), (2), (3), (4); CREATE TABLE b ( b_id INT PRIMARY KEY, a_id INT, name VARCHAR(255) NOT NULL ); INSERT INTO b (b_id, a_id, name) VALUES (1, 1, 'foo'), (2, 1, 'bar'), (3, 1, 'asdf'), (4, 2, 'foo'), (5, 2, 'bar'), (6, 3, 'foo'); </code></pre> <p>Now my problem is to find entries in <code>a</code> that are missing <code>name</code> entries in table <code>b</code>. E.g. I need to make sure each entry in <code>a</code> has at least the <code>name</code> entries <code>"foo"</code> and <code>"bar"</code> in table <code>b</code>. Hence the query should return something similar to:</p> <pre><code>a_id = 3 is missing name "bar" a_id = 4 is missing name "foo" and "bar" </code></pre> <p>Since both tables are potentially huge in Akonadi, performance is of utmost importance.</p> <p>One solution in MySQL would be:</p> <pre><code>SELECT a.a_id, CONCAT('|', GROUP_CONCAT(name ORDER BY NAME ASC SEPARATOR '|'), '|') as names FROM a LEFT JOIN b USING( a_id ) GROUP BY a.a_id HAVING names IS NULL OR names NOT LIKE '%|bar|foo|%'; </code></pre> <p>I have yet to measure the performance tomorrow, but severly doubt it's any fast for tens of thousand of entries in <code>a</code> and thrice as many in <code>b</code>. Furthermore we want to support SQLite and PostgreSQL where to my knowledge the <code>GROUP_CONCAT</code> function is not available.</p> <p>Thanks, good night.</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.
 

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