2012-04-30 54 views
0

我已經搜索,但無法找到任何我需要的東西。 我想創建一個存儲函數,它將從輔助字段收集數據,並返回逗號分隔的項目列表作爲返回字符串。我似乎無法找到任何方式採用可變我在函數創建,並通過記錄集迭代和每個結果追加到變量,這樣我可以回到它..見下圖:MySQL存儲函數 - 追加字符串

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要約類我在我的PHPand填充進入查詢):

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 

回答

3

爲什麼不

SELECT GROUP_CONCAT(meta_option SEPARATOR ',') 
FROM offer_metas 
WHERE category = searchCat AND offer_id = searchProd; 
+0

默認分離器已經是逗號,但無論如何+1 !!! – RolandoMySQLDBA

+0

無論如何,我結束了使用Group_Concat ..似乎已經在該功能內工作,一切都很好。我的答案已經更新了我的最終查詢。 – Silvertiger