Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL query using variable as table name in LEFT JOIN

SELECT var1,var2,var3,table_name 
FROM table1 LEFT JOIN table_name on var3=table_name.id

Meaning I want to dynamically left join table, depending on value of table_name from table1, since var3 is taken from there.

But the above query results in

table table_name does not exist

My mistake of mysql limitation?

like image 855
selytch Avatar asked Sep 05 '10 14:09

selytch


People also ask

Can we use right and left join in a same query?

The only you can do that is by using UNION .

Are left JOINs allowed MySQL?

Introduction to MySQL LEFT JOIN clauseThe LEFT JOIN allows you to query data from two or more tables. Similar to the INNER JOIN clause, the LEFT JOIN is an optional clause of the SELECT statement, which appears immediately after the FROM clause.


1 Answers

Table names, as well as column names, can't be dynamic in an SQL query. So you have to apply your logic programmatically, using 2 queries, or with a stored procedure, see an example here: http://forums.mysql.com/read.php?98,126506,126598#msg-126598

like image 149
Damien Avatar answered Oct 26 '22 11:10

Damien