sql left join for two tables using a CONCAT string as the argument

Beyerz picture Beyerz · Mar 13, 2012 · Viewed 9.7k times · Source

I need to get a title from table 2, table 2 has title and id column. Table 1 has some data and three of these columns concatenated together makeup the id that can be found in table 1.

I used CONCAT_WS() function and gave this column an alias name and need to use the Alias for the on argument(At least this is what I understood I needed to do)

I thought this could be a simple left join, yet it is not working for me.

This is my query

SELECT
    table_openers.mail,
    table_openers.f_name,
    table_openers.l_name,
    table_openers.Quality,
    CONCAT_WS('-',
            table_openers.esp,
            table_openers.acc,
            table_openers.group) as 't1aid',
    table_groups.aid,
    table_groups.group_name
FROM
    lance_mailstats.table_openers
        LEFT JOIN
    lance_mailstats.table_groups ON table_groups.aid = t1aid;

I get results for mail, f_name, l_name, Quality and t1aid, but the aid and group_name columns of the second table return null.

Answer

Luca picture Luca · Mar 13, 2012

I feel like you can't use an alias in the ON clause. Try doing

LEFT JOIN
    lance_mailstats.table_groups ON table_groups.aid = CONCAT_WS('-',
            table_openers.esp,
            table_openers.acc,
            table_openers.group);

"You can use the alias in GROUP BY, ORDER BY, or HAVING clauses to refer to the column" (from dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html).

And "The conditional_expr used with ON is any conditional expression of the form that can be used in a WHERE clause" (from dev.mysql.com/doc/refman/5.1/en/join.html).

So as a logical inference you're not allowed to use aliases in ON clauses.