Search code examples
mysqlmysql-error-1054

Mysql subquery with conditional left outer join


Trying to use parameter from external query in subquery FROM clause.

tbl1:
| id | val1 | str1 |
| 1  | 12   | sbc  |
| 2  | 22   | sds  |

tbl2:
| id | val1 | str1 |
| 1  | 1    | cp   |

Trying to write the following query:

select * from
    tbl1 t, (select * from tbl2 where t.id = tbl2.id and tbl2.val1 = 1) tb12;

Expected output:

| id | val1 | str1 | id   | val1 | str1 |
| 1  | 12   | sbc  | 1    | 1    | cp   |
| 2  | 22   | sds  | null | null | null |

Yet it fails with the error:

/* SQL Error (1054): Unknown column 't.id' in 'where clause' */

What am I doing wrong here?


Solution

  • SELECT  *
    FROM    tbl1 t
    LEFT JOIN
            tbl2 t2
    ON      t2.id = t.id
            AND t2.val1 = 1