user5429087
user5429087

Reputation: 169

Using dynamic column and table names in Join in MariaDB/MySQL

I'm not sure how to do this or if it's even possible but conceptually it would look something like this:

SELECT item_id, CONCAT('field_data_', `field_name`) AS t2,     CONCAT(`field_name`, '_value') AS f
FROM (
   BIG SELECT STATEMENT
) AS t1
JOIN {t2} ON t2.{f} = t1.item_id

Where {t2} in the JOIN is coming from the created field via concatenation and {f} in the JOIN is coming from the other field created via concatenation.

That is {t2} and {f} are substituted with the values of the fields instead being taken as literally t2 & f. I thought it might be done with something like COLUMN_GET but I'm not sure how to make that work in the JOIN part.

Is this possible?

Upvotes: 0

Views: 561

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562310

No, this is not possible. Table names, column names, and all other elements of the SQL query must be fixed at the time the query is parsed. You can't make a query do different things based on what it discovers about data during execution.

This would be like asking, "Can I write a Java function that returns a value, but the value it returns determines which function I call?"

Upvotes: 1

Related Questions