I am having quite a frustrating problem with a stored function in MySQL.
I have a database full of session data from users connecting to a wireless hotspot. I am trying to select individual user download statistics from within a selected month. My problem is that the subquery within the function seems to ignore the mac field in the WHERE statement. Here is my code:
CREATE FUNCTION get_month_download(mo varchar(45), box int(11), mac varchar(45)) RETURNS DOUBLE
BEGIN
DECLARE dwnld double;
IF mo IS NULL THEN
SET mo := CONCAT(CONCAT(YEAR(NOW()), '-', MONTH(NOW())),'-','01');
END IF;
SET dwnld := (
SELECT SUM(`tx_bytes`)
FROM `session`
WHERE `assoc_time` > UNIX_TIMESTAMP(mo)
AND `disassoc_time` < UNIX_TIMESTAMP(DATE_ADD(mo, INTERVAL 1 MONTH))
AND `mac` = mac
AND `controller_id` = box
);
return dwnld;
END
Running this:
SELECT get_month_download('2012-09-01', '2', '00:21:5c:56:be:a3');
Returns download data for the entire table, though it is using the controller_id to filter the data.
If I run the subquery outside of the function using the same parameters, it works fine. What gives?
To be more clear, running this query:
SELECT SUM(`tx_bytes`)
FROM `session`
WHERE `assoc_time` > UNIX_TIMESTAMP('2012-09-01')
AND `disassoc_time` < UNIX_TIMESTAMP(DATE_ADD('2012-09-01', INTERVAL 1 MONTH))
AND `mac` = '00:21:5c:56:be:a3'
AND `controller_id` = '2';
returns the correct download statistic for that user. Where the function returns the statistic for all users of that controller.
I should really reflect back to what my teachers taught me in college more often. The issue was that the variable
mac, in the scope of the select statement, was seen as a field from the table, and not as my parameter from the function. So, changing the parameter name fixed the issue:This has been a ‘smack in the face’ moment. Thank you all for your help.