mysql – Pass variable value inside nested SELECT

Question:

Assuming the following query where we are selecting values, grouping them and then regrouping the result:

SELECT
    CONCAT (b.label, '|', b.slug)
FROM (
    SELECT
        group_concat(name SEPARATOR '$') AS label,
        group_concat(slug SEPARATOR '$') AS slug
    FROM (
        SELECT
            color.name,
            color.slug
        FROM color
        INNER JOIN product__colors USING ( color_id )
        WHERE product__colors.product_id = 1 -- integer fixo funciona
    ) AS a
) AS b

Output example:

azul$vermelho$branco verde|azul$vermelho$branco-verde

But the query is to be performed with the value of product__colors.product_id variable and not 1 as in the example above:

SELECT
    CONCAT (b.label, '|', b.slug)
FROM (
    SELECT
        group_concat(name SEPARATOR '$') AS label,
        group_concat(slug SEPARATOR '$') AS slug
    FROM (
        SELECT
            color.name,
            color.slug
        FROM color
        INNER JOIN product__colors USING ( color_id )
        WHERE product__colors.product_id = ? -- integer variável não funciona
    ) AS a
) AS b

Question

How can we pass a variable value to the innermost condition?

Answer:

It really wasn't clear maybe but you say "doesn't run", I tested it here and it ran, maybe the way you're declaring the variable is giving you some problem, this part you didn't demonstrate, follow my test.

set @variavel = 1;
select 
    CONCAT(b.label,b.slug)    
from (
    SELECT
        group_concat(func_nome SEPARATOR '$') AS label,
        group_concat(func_id SEPARATOR '$') AS slug
    FROM (
        SELECT
            f.func_nome,
            f.func_id
        FROM tab_funcionario f
        INNER JOIN tab_jornada_mot USING ( func_id )
        WHERE tab_jornada_mot.func_id = @variavel -- declarada no inicio do código
    ) AS a
) as b

I made some changes to the names of tables/attributes because I tested it in a DB that I had ready, but I believe it is clear.

Maybe you made the variable declaration in another way ex:

declare variavel int;
select ...

This way I haven't tested it, but as above it works.

Scroll to Top