Mysql JOIN ON IF ()?

I am trying to use sql, for example:

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 this?

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

Is this recommended if possible?


update
so

basically a table templatesis a table containing all the information that each template should have, for example, name, identifier, description

then you have tables templates_x, these tables contain fields that are unique to each type of template.
(There is a lot of availability of one table with zero fields for those that are not applicable, it is impractical).

Tables are named templates_x, but the corresponding x is stored in the template table as an int flag.

templates_x templates t_id.

, ?

+5
3

- ?

, (join other) SQL (. MySQL PreparedStatement).

- , , , :

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)
+3

, .

:

SELECT 
  CASE 
    WHEN t.type = 0 THEN [templates_email]
    WHEN t.type = 1 THEN [templates_sms]
    WHEN t.type = 2 THEN [templates_fax]
  END AS [selected_field]
FROM 
  t
LEFT JOIN t1 ON t.t_id = t1.t_id
LEFT JOIN t2 ON t.t_id = t2.t_id
LEFT JOIN t3 ON t.t_id = t3.t_id
+3

, - ( ):

SELECT t.*, t2.* FROM templates t
LEFT JOIN templates_email t2
ON t.t_id = t2.t_id
WHERE t.t_type = 0
UNION
SELECT t.*, t2.* FROM templates t
LEFT JOIN templates_sms t2
ON t.t_id = t2.t_id
WHERE t.t_type = 1
UNION
SELECT t.*, t2.* FROM templates t
LEFT JOIN templates_fax t2
ON t.t_id = t2.t_id
WHERE t.t_type NOT IN (0,1)

:

SELECT t.*, t1.*, t2.*, t3.*
FROM templates t    
LEFT JOIN templates_email t1
ON t.t_id = t1.t_id
AND t.type_id = 0
LEFT JOIN templates_sms t2
ON t.t_id = t2.t_id
AND t.type_id = 1
LEFT JOIN templates_fax t3
ON t.t_id = t3.t_id
AND t.type_id NOT IN (0,1)

..and live with all the NULL columns.

+2
source

All Articles