MySQL存储过程的循环结果集

时间:2014-05-08 13:47:52

标签: mysql mysql-workbench

这是我的存储函数,它从多个表中获取完整地址

DELIMITER $$

CREATE FUNCTION `get_Address` (Id INT)
RETURNS varchar (250)
BEGIN
DECLARE address varchar (250);

DECLARE state varchar (250);
DECLARE gov varchar (250);
DECLARE city varchar (250);
DECLARE hood varchar (250);
DECLARE street varchar (250);
DECLARE building varchar (250);
DECLARE floor varchar (250);

declare cr1 cursor FOR
SELECT 
    s.state_Name,
    g.governorate_Name,
    c.city_Name,
    h.hood_Name,
    st.street_Name,
    a.address_Building,
    a.address_Floor
FROM
    addresses AS a
        INNER JOIN
    states AS s ON s.state_Id = a.state_Id
        INNER JOIN
    governorates AS g ON g.governorate_Id = a.governorate_Id
        INNER JOIN
    cities AS c ON c.city_Id = a.city_Id
        INNER JOIN
    hoods AS h ON h.hood_Id = a.hood_Id
        INNER JOIN
    streets AS st ON st.street_Id = a.street_Id
WHERE
    a.address_Id = Id;

OPEN cr1;

FETCH cr1 INTO state, gov, city , hood , street, building ,floor;

CLOSE cur1;
RETURN address;
END

我需要得到这样的东西

address = state + gov + city + hood + street + building + floor;

我需要返回所有结果集并使用PHP创建完整地址 或循环结果并在MYSQL中创建完整地址并返回varchar

1 个答案:

答案 0 :(得分:1)

您无法在MySQL中返回结果集,因为我们没有任何此类数据类型。

您可以使用

concat_ws(" ",state , gov , city , hood , street , building , floor) as address 
如果您需要一次,请直接在查询中

如果你要多次使用它,那么最好制作一个汇总表


但这可能是另一种解决方案:
1)创建临时表
2)获取结果并将其输入到临时表中
3)调用tmp表以获取地址

这就是我的意思:

DELIMITER $$
DROP PROCEDURE IF EXISTS get_Address$$
CREATE PROCEDURE `get_Address` (IN Id INT)
BEGIN
  CREATE TABLE tmp_address(ID INT,address VARCHAR(255));

  INSERT INTO tmp_address
  SELECT 
    a.address_Id,
    CONCAT_WS(" ",s.state_Name,
        g.governorate_Name,
        c.city_Name,
        h.hood_Name,
        st.street_Name,
        a.address_Building,
        a.address_Floor) as address
  FROM
    addresses AS a
        INNER JOIN
    states AS s ON s.state_Id = a.state_Id
        INNER JOIN
    governorates AS g ON g.governorate_Id = a.governorate_Id
        INNER JOIN
    cities AS c ON c.city_Id = a.city_Id
        INNER JOIN
    hoods AS h ON h.hood_Id = a.hood_Id
        INNER JOIN
    streets AS st ON st.street_Id = a.street_Id
  WHERE
    a.address_Id = Id;

END$$
DELIMITER ;

希望这有帮助! :)