我想用我的数据库中的数据返回带有mysql的10个json字符串,但是我得到了以下错误:SQL错误(1172):结果包含多行! 是的我知道结果包含更多行,它们是10,问题是如何在不同的行中打印它们?
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
回复
答案 0 :(得分:0)
不得使用功能。 也许从这个查询定义视图?像这样:
create or replace view userquery select if(semail is not null,
CONCAT('{"response":1,"id":',sid,',"email":"',semail,'","name":"',sname,'","lastname":"',slastname,'"}'),"0") response,
email,lastname,name FROM user ;
并查询
select response from userquery where ...
或者只是在查询中使用“if”,没有功能。
答案 1 :(得分:0)
是的,最后我不会使用循环和光标来响应此查询的响应,我将使用这样的json字符串:
BEGIN
DECLARE response TEXT;
SELECT CONCAT('{',GROUP_CONCAT(id SEPARATOR ','),'}') INTO response
FROM user
WHERE email LIKE CONCAT('%',value,'%')
OR lastname LIKE CONCAT('%',value,'%')
OR name LIKE CONCAT('%',value,'%');
IF( response IS NOT NULL ) THEN
RETURN response;
ELSE
RETURN CONCAT('{"response":0}');
END IF;
END
我认为sql游标和循环用于获得更高级的结果,无论如何工作就像我在这里做的那样,tcx!