I'm facing a problem very similar to this issue:
MySQL stored procedure only returns last row of data
Let me explain the scenario first. I'm using phplist and I have created a custom attribute acting as "per user token"; it is used to create a custom unsubscribe links. Sometimes I'm in the need to get such token manually knowing the user email address.
So, here is the two involved tables are (note: only relevand fields here):
With dbeaver ide, executing the following query I correctly get the user token:
SELECT value AS token FROM phplist_user_user_attribute WHERE attributeid=3 and userid=(SELECT MAX(`id`) FROM phplist_user_user WHERE `email`='useremail@domain.ext');
If I put this query inside a stored procedure instead it always returns the very last token inserted to the table, regardless the correctness of email:
CREATE DEFINER=`root`@`%` PROCEDURE `phplist`.`GetTokenFromEmail`(IN `email` VARCHAR(255))
BEGIN
SELECT value AS token
FROM phplist_user_user_attribute
WHERE attributeid=3
and userid=(SELECT MAX(`id`)
FROM phplist_user_user
WHERE `email`=email);
END
Checking at phplist_user_user_attribute table it equals to the very last row:
This is a standard/default phplist installation, so I'm probably doing something wrong with the procedure I don't really understand what.
Thank you for any help!
WHERE `email`=email
Both columns are taken from phplist_user_user
table - so the condition value is always TRUE until phplist_user_user.email
is NULL.
Remember - if query's rowsource contains more than one table (including a case of copies of the same table) then specify table name/alias for EACH column name.