我已经搜索过,但找不到任何我需要的东西。我想创建一个存储函数,该函数将从辅助字段收集数据并返回逗号分隔的项目列表作为返回字符串。我似乎找不到任何方法来获取我在函数中创建的变量并遍历记录集并将每个结果附加到变量中,以便我可以返回它..见下文:
BEGIN
DECLARE searchCat INT;
DECLARE searchProd INT;
DECLARE metas CHAR;
SET searchCat = cat;
SET searchProd = prod;
SELECT * FROM offer_metas WHERE category = searchCat AND offer_id = searchProd
gatherMeta: LOOP
metas = metas + "," + meta_option;
ITERATE gatherMeta;
END LOOP gatherMeta;
RETURN metas;
END
该函数不会保存,因为我在“metas = metas + meta_option;”上的语法。我正在寻找的是将“meta_option”的当前字段值附加到当前变量“metas”的命令,这样我就可以在最后返回一个完整的列表。
任何的想法?
更新 - 解决方案
BEGIN
DECLARE metas VARCHAR (300);
SELECT GROUP_CONCAT(CONCAT(mn.title,'=',offer_metas.meta_option) ORDER BY mo.cat_seq ASC) INTO metas
FROM offer_metas
LEFT JOIN meta_options as mo ON mo.id = offer_metas.meta_option
LEFT JOIN meta_names AS mn ON mn.category = mo.category AND mn.seq = mo.cat_seq
WHERE offer_metas.category = searchCat
AND offer_metas.offer_id = searchProd
ORDER BY cat_seq ASC;
RETURN metas;
END
然后我刚刚将我的 SQL 查询更新为如下(1 是我的 PHP 中的报价类别并填充到查询中):
SELECT offers.*, s.short_name AS sponsorName, s.logo AS sponsorLogo, getMetas(1,offers.id) AS metas
FROM offers
LEFT JOIN sponsors AS s ON s.id=offers.carrier
GROUP BY offers.id
ORDER BY end_date ASC