创建一个 MySQL 函数
Create a MySQL function
在我的 mysql 数据库中,我有 2 个表“brands”和“models”
CREATE table brands (
id int(11),
brand_name varchar(20));
CREATE TABLE models (
id int(11),
idBrand int(11),
model_name varchar(20));
我想编写一个函数来显示这样的请求结果:
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
您可以使用group_concat
函数:
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;
或者如果你不想selectid,这也是有效的:
select brand_name, group_concat(model_name)
from brands b join models m
on b.id = m.idBrand
group by brand_name;
如果你想要一整套 returnd 那么你可以创建程序:
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
并这样称呼它:
call test_proc();
因为正如您在这里看到的:https://dev.mysql.com/doc/refman/8.0/en/create-function-udf.html 函数不能 return 这种数据...
您可以使用group_concat Mysql函数得到想要的结果,如下所示:
Select br.brand_name,
group_concat(mod.model_name SEPARATOR ',') AS model_name
from brands br join models mod
on br.id = mod.idBrand
group by br.brand_name;
希望对您有所帮助!
在我的 mysql 数据库中,我有 2 个表“brands”和“models”
CREATE table brands (
id int(11),
brand_name varchar(20));
CREATE TABLE models (
id int(11),
idBrand int(11),
model_name varchar(20));
我想编写一个函数来显示这样的请求结果:
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
您可以使用group_concat
函数:
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;
或者如果你不想selectid,这也是有效的:
select brand_name, group_concat(model_name)
from brands b join models m
on b.id = m.idBrand
group by brand_name;
如果你想要一整套 returnd 那么你可以创建程序:
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
并这样称呼它:
call test_proc();
因为正如您在这里看到的:https://dev.mysql.com/doc/refman/8.0/en/create-function-udf.html 函数不能 return 这种数据...
您可以使用group_concat Mysql函数得到想要的结果,如下所示:
Select br.brand_name,
group_concat(mod.model_name SEPARATOR ',') AS model_name
from brands br join models mod
on br.id = mod.idBrand
group by br.brand_name;
希望对您有所帮助!