Considering the table orders
:
+-----------+----------------+
| AccountID | AccountOrderID |
+-----------+----------------+
| 1 | NULL |
| 5 | NULL |
| 1 | NULL |
| 6 | NULL |
| 5 | NULL |
| 2 | NULL |
| 6 | NULL |
| 4 | NULL |
| 4 | NULL |
| 5 | NULL |
+-----------+----------------+
How can I assign an incremental ID to AccountOrderID
relatively to Account ID
, such that it will result like:
+-----------+----------------+
| AccountID | AccountOrderID |
+-----------+----------------+
| 1 | 1 |
| 5 | 1 |
| 1 | 2 |
| 6 | 1 |
| 5 | 2 |
| 2 | 1 |
| 6 | 2 |
| 4 | 1 |
| 4 | 2 |
| 5 | 3 |
+-----------+----------------+
So far I was using the users
with a column called LastOrderID
and a trigger to increment it alongside with the AccountOrderID
(which works fine):
DELIMITER $$
CREATE TRIGGER `new_order` BEFORE INSERT ON maindb.orders
FOR EACH ROW BEGIN
UPDATE users
SET LastOrderID = LastOrderID + 1
WHERE AccountID = NEW.AccountID;
SET NEW.AccountOrderID = (SELECT LastOrderID FROM Credentials WHERE AccountID = NEW.AccountID);
END;
$$
DELIMITER ;
But I believe that the users
table shouldn't be used for this purpose: is there an other way to achive this result?
EDIT
Even if it's exactly what GMB said, here is an answer offering a similar example: https://stackoverflow.com/a/2404587/9373031