I have 2 tables:
user messages
+---------+ +----------------+
|id|credit| |id|user_id| ... |
+---------+ +----------------+
|01| 05 | |01| 01 | ... |
|02| 01 | |02| 01 | ... |
|03| 00 | |03| 01 | ... |
+---------+ |04| 02 | ... |
|05| 02 | ... |
|06| 03 | ... |
+----------------+
I need to select n messages from messages where n=user.credit. The query I would like to execute a query like:
SELECT *
FROM user u JOIN messages m ON u.id = m.user_id LIMIT u.credit
WHERE user in ...;
And should return rows 01, 02, 03, 04 but not 05, 06.
I know I can't write LIMIT u.credit but want that behavior, limit the number of messages fetched for each user in function of the value of the credits they have (user 01 whit limit of 5, user 02 with limit of 1 and so on) and I want to fetch all the messages all at once to avoid having to do a COUNT and then a SELECT for each user.
I'm using MySQL with InnoDB
u.id == m.user_idshould beu.id = m.user_idLIMIT, not an expression.u.creditvalue into a variable, then builds a query-string using that value as the limit and then having the procedure execute that query.