mysqlsqlmysql-function

Create a MySQL function


In my mysql dababase i have 2 tables "brands" and "models"

CREATE table brands (
id int(11),
brand_name varchar(20));

CREATE TABLE models (
id int(11),
idBrand int(11),
model_name varchar(20));

I want to write a functions allowing me to display a result of requet like this :

Brand_name      model_name
brand_1         model_1_1, model_1_2, model_l_3
brand_2         model_2_1, model_2_2, model_2_3  

Solution

  • You can use group_concat function:

    select b.id, max(brand_name), group_concat(model_name)
    from brands b join models m
    on b.id = m.idBrand
    group by b.id;
    

    Or if you want not to select id, this is also valid:

    select brand_name, group_concat(model_name)
    from brands b join models m
    on b.id = m.idBrand
    group by brand_name;
    

    Here is a demo

    If you want to have a whole set returnd then you can create procedure:

    CREATE procedure test_proc ()
    
    BEGIN
    
     select brand_name, group_concat(model_name) model_name
     from brands b join models m
     on b.id = m.idBrand
     group by brand_name;
    
    END
    

    And call it like this:

    call test_proc();
    

    Because as you can see here: https://dev.mysql.com/doc/refman/8.0/en/create-function-udf.html functions can not return this kind of data...