I want to update column user
with the last 6 characters replaced by id
padded with zero. All keys under column user
are in the format ^[A-Z]{2}[0-9]{8}$
. For example, here's some sample data:
MariaDB [test]> SELECT * FROM users ORDER BY id ASC LIMIT 3;
+----+------------+
| id | user |
+----+------------+
| 1 | AS12491264 |
| 2 | LQ10240183 |
| 3 | MR12037108 |
+----+------------+
3 rows in set (0.00 sec)
The expected result is:
+----+------------+
| id | user |
+----+------------+
| 1 | AS12000001 |
| 2 | LQ10000002 |
| 3 | MR12000003 |
+----+------------+
I worked out the following two queries but both fail:
UPDATE users AS u
SET u.user = (
SELECT
CONCAT(
SUBSTRING(s.user, 0, 4),
LPAD(s.id, 6, '0')
)
FROM users AS s
WHERE s.id = u.id
);
UPDATE users AS u
INNER JOIN (
SELECT
s.id AS id,
CONCAT(
SUBSTRING(s.user, 0, 4),
LPAD(s.id, 6, '0')
) AS data
FROM users AS s
) AS s ON s.id = u.id
SET u.user = s.data;
Both fail and give this result:
+----+--------+
| id | user |
+----+--------+
| 1 | 000001 |
| 2 | 000002 |
| 3 | 000003 |
+----+--------+
Here's the DB schema (fetched from mysqldump
):
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user` varchar(64) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user` (`user`)
) ENGINE=InnoDB AUTO_INCREMENT=8964 DEFAULT CHARSET=utf8;
I am running on MariaDB 10.1.38.