Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql JOIN ON IF()?

Tags:

sql

join

mysql

I am trying to use sql such as this:

SELECT t.*, t2.* FROM templates t
LEFT JOIN IF(t.t_type = 0,'templates_email',
IF(t.t_type = 1,'templates_sms','templates_fax')) t2
ON t.t_id = t2.t_id;

Is it possible to do something like that?

basically I want to join on one of three tables based on the value from the row.

Is this recommended if it is possible?


update
So,

basically the templates table is the table that contains all the information that every template must have, eg name, id, description

then you have the templates_x tables these tables contain the fields that are unique to each template type.
(There are quite a few and having a single table with null fields for those not applicable is not practical).

The tables are called templates_x however the appropriate x is stored in the templates table as an int flag.

The join between the templates_x tables and the templates table is through the t_id.

So what do you suggest?

like image 447
Hailwood Avatar asked Sep 27 '10 23:09

Hailwood


1 Answers

Is it possible to do something like that?

No, you can't use dynamically assigned tables (join or otherwise) without using dynamic SQL syntax (See MySQL's PreparedStatement syntax).

This non-dynamic re-write of your pseudo-query assumes that the three template tables you join to all have the same number of columns, and the same data types:

SELECT t.*, 
       te.*
  FROM TEMPLATES t
  JOIN TEMPLATES_EMAIL te ON te.t_id = t.t_id
 WHERE t.t_type = 0
UNION
SELECT t.*, 
       ts.*
  FROM TEMPLATES t
  JOIN TEMPLATES_SMS ts ON ts.t_id = t.t_id
 WHERE t.t_type = 1
UNION
SELECT t.*, 
       tf.*
  FROM TEMPLATES t
  JOIN TEMPLATES_FAX tf ON tf.t_id = t.t_id
 WHERE t.t_type NOT IN (0, 1)
like image 53
OMG Ponies Avatar answered Sep 23 '22 02:09

OMG Ponies