sqlite LEFT OUTER JOIN multiple tables

ferpega picture ferpega · Jun 19, 2012 · Viewed 49.2k times · Source

In this example we have 3 related tables on a SQLite database:

CREATE TABLE test1 (
    c1 integer,
    primary key (c1)
);
CREATE TABLE test2 (
    c1 integer,
    c2 integer,
    primary key (c1, c2)
);    
CREATE TABLE test3 (
    c2 integer,
    c3 integer,
    primary key (c2)
);

Now I need to join all tables:

 test1 -> test2 (with c1 column)
          test2 -> test3 (with c2 column).

I have tried this solution but it doesn't run:

SELECT 
   * 
   FROM test1 a 
        LEFT OUTER JOIN test2 b
                        LEFT OUTER JOIN test3 c
                          ON c.c2 = b.c2 
          ON b.c1=a.c1 

It gives me an error: near "ON": syntax error.

Any help ?

Answer

Nathaniel Ford picture Nathaniel Ford · Jun 19, 2012

This is a simple misplacement of your ON statement. This conforms to SQL standard:

SELECT * 
FROM test1 a 
LEFT OUTER JOIN test2 b ON b.c1=a.c1 
LEFT OUTER JOIN test3 c ON c.c2=b.c2 

This is explained in further depth here.