[英]MySQL CREATE FUNCTION result with multiple records gives error #1172
I have the following 3 tables: 我有以下3表:
table "name" --------------- id name --------------- 1 book 2 pen table "color" ------------------ id color ------------------ 1 red 2 yello 3 green 4 pink table "both" ------------------------ id name color ---------------------- 1 1 1 2 1 2 3 1 3 4 2 2
and I have the following function: 并且我具有以下功能:
DELIMITER //
CREATE FUNCTION get_word(n VARCHAR(20))
RETURNS VARCHAR(10)
READS SQL DATA
DETERMINISTIC
BEGIN
DECLARE b VARCHAR(20);
SELECT `color`.`color` INTO b FROM `name`
LEFT JOIN `both`
ON `name`.`id`=`both`.`name`
LEFT JOIN `color`
ON `color`.`id`=`both`.`color`
WHERE `name`.`name`=n;
RETURN b;
END//
DELIMITER ;
now when I run SELECT get_word('pen') it returns yellow which is what is expect. 现在,当我运行SELECT get_word('pen')时,它返回黄色 ,这是预期的结果。
but when I run the code SELECT get_word('book') it get error: #1172 - Result consisted of more than one row 但是,当我运行代码SELECT get_word('book')时 ,出现错误:# 1172-结果包含多于一行
my Question: What to do so this function works with multiple records as well as single record which it does when I search for "pen"? 我的问题:怎么做?此功能可用于多条记录,也可用于搜索“笔”的单条记录? thanks 谢谢
UPDATE: 更新:
If use the query without the function as follow, it just works fine: 如果使用不带以下功能的查询,则可以正常工作:
SELECT `color`.`color` AS b FROM `name`
LEFT JOIN `both`
ON `name`.`id`=`both`.`name`
LEFT JOIN `color`
ON `color`.`id`=`both`.`color`
WHERE `name`.`name`='book';
and it returns: 它返回:
**b** red yellow green
Well, it seems that you want a resultset (more than one value) 好吧,似乎您想要一个结果集(多个值)
But a mysql stored function cannot return a resultset (see doc : Restrictions for Stored Functions). 但是mysql存储函数不能返回结果集(请参阅doc :存储函数的限制)。
Solution 1 : use a stored procedure 解决方案1 :使用存储过程
CREATE PROCEDURE get_word(n VARCHAR(20))
BEGIN
SELECT `color`.`color`
FROM `name`
LEFT JOIN `both`
ON `name`.`id`=`both`.`name`
LEFT JOIN `color`
ON `color`.`id`=`both`.`color`
WHERE `name`.`name`=n;
END
Solution2 : return a concatenated string 解决方案2 :返回一个串联的字符串
something like "green, yellow, blue"
GROUP_CONCAT can do that easily. 诸如"green, yellow, blue"
GROUP_CONCAT之类的内容可以轻松实现。 see this stackoverflow question for example 例如,请参阅此stackoverflow问题
尝试在where
之后使用group by,例如,尝试group by id
或表中唯一的内容添加group by id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.