0

Does mysql got cover IF ELSE to select the table dynamically ?

The link here show's IF THEN is for the value, but how can the IF THEN / IF ELSE can achieve to select the table like below :

For example the dynamic table is 'othertable'

 SELECT t1.etc,t2.etc,othertable.etc

 FROM table1 AS t1,table2 AS t2, IF(t1.value=3,table3,table4) AS othertable

 WHERE othertable.table1_id = t1.id

1 Answer 1

0

You could achieve something like this with a union.

SELECT t1.* FROM table1 t1
JOIN table_a ta ON (...)
WHERE t1.value = 3
UNION ALL
SELECT t1.* FROM table1 t1
JOIN table_b tb ON (...)
WHERE t1.value = 2

For each row where t1.value =3, a join with table_a is done, for each row where t1.value = 2, table_b is joined. The union adds the results together.

You just need to make sure that the two conditions are mutually exclusive. If you can't ensure this, you can get rid of duplicates in your result set by using UNION instead of UNION ALL.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.