This is necessary to do in programming, but if you really need to do it in Mysql, an output would be to mount a procedure
that calculates and returns to you.
I’ve put together a very simple one that works for the case mentioned in the question, but needs to be improved for other treatments, it’s basically a light of what can be done:
Creation of PROCEDURE
DELIMITER $$
DROP PROCEDURE IF EXISTS selectCotas$$
CREATE PROCEDURE selectCotas(cota int(11))
BEGIN
DECLARE _id INT(11);
DECLARE _valor INT(11);
DECLARE restante INT(11) DEFAULT cota;
DECLARE ids TEXT DEFAULT '';
DECLARE fim TINYINT(1) DEFAULT 0;
DECLARE curs CURSOR FOR SELECT id, valor FROM cotas WHERE valor <= cota ORDER BY valor DESC;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET fim = 1;
OPEN curs;
REPEAT
FETCH curs INTO _id, _valor;
IF (fim = 0) THEN
IF (_valor <= restante) THEN
SET restante = restante - _valor;
IF (ids = '') THEN
SET ids = _id;
ELSE
SET ids = CONCAT(ids, ', ', _id);
END IF;
END IF;
END IF;
UNTIL (fim or restante = 0) END REPEAT;
CLOSE curs;
SET @sql = CONCAT('SELECT * FROM cotas WHERE id IN (', ids, ')');
PREPARE stmt1 FROM @sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END$$
DELIMITER;
Running
call selectCotas(2000);
Return
+----------------------------------+
| id | valor | admin |
| 200| 400| bb|
| 356| 1000| bb|
| 567| 600| bb|
+----------------------------------+
select sum(value) from produtcs From the description of your problem I believe this solves.
– Lucas Augusto Coelho Lopes