Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
657 views
in Technique[技术] by (71.8m points)

conditional join in mysql

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...