views:

611

answers:

3

Hi,

I have a table id1, id2, type. type is an enumerated value containing a name of another table. I'd like to preform a join with the name of the table of type. For example:

switch($type)
case 'table1':
   join table1;
   break;
case 'table2':
   join table2;
   break;

How can I achieve this?

+1  A: 

ugly way:

Table Types, T1, T2:

SELECT ... FROM Types, T1 , where Types.ID=T1.Types_ID AND Types.TYPE='TABLE1'
UNION
SELECT ... FROM Types, T2 , where Types.ID=T2.Types_ID AND Types.TYPE='TABLE2'
Steve B.
Isn't that just "the way"? Stop using my name.
stevedbrown
It's "A" way. It looks ugly, I was hoping there was a better. But then again most SQL beyond "SELECT * FROM X" looks ugly to me ;)
Steve B.
+1  A: 

You can't do it directly like that... you can do something like this though (not very pretty...):

SELECT
t.id,
t.type,
t2.id AS id2,
t3.id AS id3

FROM t
LEFT JOIN t2 ON t2.id = t.id AND t.type = 't2'
LEFT JOIN t3 ON t3.id = t.id AND t.type = 't3'
Greg
+1  A: 

In addition to previous answer: You can combine the two left joins results by using IF statement: IF(t.type= 't2', t2.id, t3.id) as type_id

You can see another mysql conditional joins example at mysqldiary.com

Ilan