问题
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