Why sql function return count of all and single select return correct value?

你离开我真会死。 提交于 2021-02-20 04:08:30

问题


I have function that will return all of rows, but I expect 0 or 1 because Sid is unique:

CREATE DEFINER=`root`@`localhost` FUNCTION `IsInDatabase`(sId VARCHAR(21)) RETURNS tinyint(1)
BEGIN
RETURN (SELECT COUNT(Id) FROM table WHERE SId =sid);
END

When executed directly,

SELECT COUNT(Id) FROM table WHERE SId ='87882118' 

will return exactly what I need: '1' or '0'. Why is my function not working properly ?


回答1:


It's because MySQL is not case sensitive and so SId and sid are the same name, and it doesn't know which one you are referring to in the query, so it picks one (the same one in both instances) and of course it matches for every row. Try changing your input parameter name:

CREATE DEFINER=`root`@`localhost` FUNCTION `IsInDatabase`(sIdin VARCHAR(21)) RETURNS tinyint(1)
BEGIN
    RETURN (SELECT COUNT(Id) FROM table WHERE SId =sIdin);
END


来源:https://stackoverflow.com/questions/54914014/why-sql-function-return-count-of-all-and-single-select-return-correct-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!