1

虽然它工作得很好,但我想学习(我在网上阅读并寻找示例但找不到任何东西)如果我在下面提出的问题可能。正如您在我的函数中看到的那样,我连接 3 列以作为一个字符串返回,并在我的 PHP 代码中将其分解以使用它们。

我可以一次单独返回这 3 列而不在 PHP 中使用CONCAT_WS()和不使用吗?explode

谢谢

我的 MYSQL 功能:

DROP FUNCTION IF EXISTS function_institute_university;

DELIMITER $$

CREATE FUNCTION function_institute_university (IN_partnership_id INTEGER(11))
RETURNS VARCHAR(250) DETERMINISTIC 
BEGIN
    DECLARE InsCode_UniID_UniCode VARCHAR(250);

    SELECT
        CONCAT_WS('~',
            UPPER(institute.Code),
            university.id,
            UPPER(university.UnivAcronym)
        ) INTO InsCode_UniID_UniCode
    FROM partnership
    LEFT JOIN institute ON institute.id = partnership.iid
    LEFT JOIN university ON university.id = partnership.uid
    WHERE
        partnership.id = IN_partnership_id AND
        partnership.active = '1'
      LIMIT 1;

    RETURN InsCode_UniID_UniCode;
END$$

DELIMITER ;

我的 PHP 代码:

$sql = "SELECT function_institute_university(15)";
$runSql = mysql_query($sql);

if(@mysql_num_rows($runSql) == 1)
{
   $newArray = mysql_fetch_array($runSql);
   list($instituteCode, $universityID, $universityCode) = explode('~', $newArray[0]);
}
4

1 回答 1

2

更新:再看一遍后,我发现您正在使用一个仅返回一个值的函数(完全被忽略),您可以将其更改为过程吗?

SQL:

DROP PROCEDURE IF EXISTS procedure_institute_university;

DELIMITER $$

CREATE PROCEDURE procedure_institute_university (IN_partnership_id INTEGER(11))
BEGIN
    SELECT
        UPPER(institute.Code) as `institiute_code`,
        university.id as `university_id`,
        UPPER(university.UnivAcronym) as `university_acronym`
    FROM partnership
    LEFT JOIN institute ON institute.id = partnership.iid
    LEFT JOIN university ON university.id = partnership.uid
    WHERE
        partnership.id = IN_partnership_id AND
        partnership.active = '1'
      LIMIT 1;
END$$

PHP:

$sql = "call procedure_institute_university(15)";
$runSql = mysql_query($sql);

if(@mysql_num_rows($runSql) == 1)
{
   $newArray = mysql_fetch_array($runSql);
   list($instituteCode, $universityID, $universityCode) = $newArray[0]['institute_code'], $newArray[0]['university_id'], $newArray[0]['university_acronym'];
}

添加了别名,以便您可以确定检索到的内容。您也可以使用mysql_fetch_assochttp://php.net/manual/en/function.mysql-fetch-assoc.php)来获取关联数组。请在阅读文档时阅读该页面中的警告消息。

于 2013-07-25T17:31:32.367 回答