Bagaimana dengan skema seperti
CREATE TABLE employee
(
employeeid INT PRIMARY KEY AUTO_INCREMENT,
firstname varchar(255)
);
CREATE INDEX part_of_firstname ON employee (firstname(4));
Itu akan memungkinkan Anda melakukan pencarian dengan cukup cepat menggunakan kunci utama alami Anda, sambil memberi Anda kunci utama buatan dan tidak memaksa untuk melakukan denormalisasi.
EXPLAIN SELECT * FROM EMPLOYEE WHERE EMPLOYEEID = 1 AND FIRSTNAME LIKE 'john%';
+----+-------------+----------+-------+---------------------------+---------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+-------+---------------------------+---------+---------+-------+------+-------+
| 1 | SIMPLE | employee | const | PRIMARY,part_of_firstname | PRIMARY | 4 | const | 1 | |
+----+-------------+----------+-------+---------------------------+---------+---------+-------+------+-------+
Tentu saja karena bagian 0001 dari kunci utama cukup unik untuk mengidentifikasi pengguna, Anda tidak perlu menanyakan nama sama sekali.
Jika Anda bersikeras untuk menghitung sebelumnya, ini akan berhasil
CREATE TABLE employee
(
employeeid INT PRIMARY KEY AUTO_INCREMENT,
specialid VARCHAR(255),
firstname VARCHAR(255)
);
CREATE INDEX employee_specialid ON employee (firstname(4));
DELIMITER ;;
CREATE TRIGGER employeeid_trigger BEFORE insert ON employee
FOR EACH ROW
BEGIN
SET new.specialid = CONCAT(LPAD((SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'employee'), 4, '0'), SUBSTRING(new.firstname, 1, 4));
END
;;
DELIMITER ;
Mengujinya:
mysql> insert into employee (firstname) values ('johnathan');
Query OK, 1 row affected (0.04 sec)
mysql> insert into employee (firstname) values ('johnathan');
Query OK, 1 row affected (0.02 sec)
mysql> insert into employee (firstname) values ('johnathan');
Query OK, 1 row affected (0.02 sec)
mysql> select * from employee;
+------------+-----------+-----------+
| employeeid | specialid | firstname |
+------------+-----------+-----------+
| 1 | 0001john | johnathan |
| 2 | 0002john | johnathan |
| 3 | 0003john | johnathan |
+------------+-----------+-----------+
3 rows in set (0.00 sec)
Ini semacam peretasan, dan information_schema tidak akan tersedia di beberapa DB yang izinnya tidak berada di bawah kendali Anda.