我想從數據庫中返回10個帶有mysql數據的json字符串,但我得到了下面的錯誤:SQL錯誤(1172):結果由多行組成! 是的,我知道結果包含更多的行,它們是10,問題是如何將它們全部打印在不同的行中?SQL結果由多個行組成
CREATE DEFINER=`root`@`localhost` FUNCTION `search_for`(`value` TEXT)
RETURNS text CHARSET latin1
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
DECLARE sid TEXT;
DECLARE semail TEXT;
DECLARE sname TEXT;
DECLARE slastname TEXT;
DECLARE response TEXT;
SELECT id,email,name,lastname INTO sid,semail,sname,slastname
FROM user WHERE email LIKE CONCAT('%',value,'%')
OR lastname LIKE CONCAT('%',value,'%')
OR name LIKE CONCAT('%',value,'%') LIMIT 10;
IF (semail IS NOT NULL) THEN
SET response = CONCAT('{"response":1,"id":',sid,',"email":"',semail,'","name":"',sname,'","lastname":"',slastname,'"}');
ELSE
SET response = CONCAT('{"response":0}');
END IF;
RETURN response;
END
後我使用遊標和循環的方法來獲取搜索結果中多行是這樣的:
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE ids TEXT;
DECLARE response TEXT;
DECLARE ids_cursor CURSOR FOR
SELECT id,email,name,lastname -- INTO ids,semail,sname,slastname
FROM user WHERE email LIKE CONCAT('%',value,'%')
OR lastname LIKE CONCAT('%',value,'%')
OR name LIKE CONCAT('%',value,'%');
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 2;
OPEN ids_cursor;
get_ids: LOOP
FETCH ids_cursor INTO ids;
IF finished = 2 THEN
LEAVE get_ids;
END IF;
SET response = CONCAT(ids,";",response);
END LOOP get_ids;
CLOSE ids_cursor;
RETURN response;
END
,我還得到一點錯誤(1328):FETCH中的變量數不正確!爲什麼?
更新
編輯下一行:
SELECT id --,email,name,lastname -- INTO ids,semail,sname,slastname
得到NULL
響應
您需要使用遊標和循環。 –
我已經試過一次,但沒有成功。現在,我知道肯定這是答案,我將嘗試修復問題 –
完成,我編輯問題 –