How to Make your Variables Dynamic in MySQL

Leveraging the GROUP_CONCAT function in MySQL allows you to concatenate query results into one row which you can then pass through as a user-defined variable in MySQL.

The SET function in MySQL allows you to add in a user-defined variable. Setting the SET equal to a query result allows you to make the variable dynamic.

However, if your query results return more than one row, you’ll need to concatenate the results into one row. For example, if you want to query your database for a bunch of ID’s, those need to be a list in order to pass them through to be a variable.

Wrapping that column in the GROUP_CONCAT allows you to return just one row.

Here’s an example of how that can look:

SET @ids = (SELECT GROUP_CONCAT(id) FROM some_table WHERE name_column LIKE "%acme%");

Lastly, if you want to reference your list of id’s in a query, the WHERE statement will have to use the FIND_IN_SET function to parse the list of id’s

Select *
from table
where FIND_IN_SET(table.id_column, @ids)

Posted

in

by

Tags: