I want to have one more column which will autoincrement depending on another column value:
ID | UserID | IDForUser
1 | 4 | 1
2 | 10 | 1
3 | 4 | 2
4 | 4 | 3
5 | 10 | 2
6 | 9 | 1
7 | 9 | 2
Is that possible?
The built-in autoincrementing algorithm does not work like this.
To compute the next IDForUser
value, search for the largest existing value with the same UserID
(or zero), and add one. If you do not want to do this in your code, you must use a trigger :
CREATE TRIGGER xxx
AFTER INSERT ON MyTable
FOR EACH ROW
WHEN NEW.IDForUser IS NULL
BEGIN
UPDATE MyTable
SET IDForUser = IFNULL((SELECT MAX(IDForUser)
FROM MyTable
WHERE UserID = NEW.UserID), 0) + 1
WHERE ID = NEW.ID;
END;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.