使用默认值(表达式)创建MYSQL表到列

时间:2011-03-07 18:44:31

标签: mysql triggers

我有一个表Employee(id,name,dept_name)。我希望id为字母数字[dddddaaaaa],前5位数字将是自动增量ID,其余4字符将是员工姓名的前4个字符。< / p>

例如,对于第一个员工姓名= John Todd,Id的自动递增部分将为00001.因此,Id将为00001JOHN

是否可以将默认表达式设置为列Id = (concat(autoincrement,substring(name,4))

我还在考虑是否可以在插入Employee之后创建触发器,触发器将更新Employee.Id。但MySql不允许从触发器触发的同一个表中更新触发器。

请帮助。

2 个答案:

答案 0 :(得分:3)

这样的架构怎么样?
CREATE TABLE employee
(
employeeid INT PRIMARY KEY AUTO_INCREMENT,
firstname varchar(255)
);

CREATE INDEX part_of_firstname ON employee (firstname(4));

这可以让你使用自然主键快速执行查找,同时为你提供一个人工主键,而不是强制反规范化。

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 |       |
+----+-------------+----------+-------+---------------------------+---------+---------+-------+------+-------+

当然,由于主键的0001部分足够独特,可以识别用户,因此您无需查询名称。

如果你坚持预先计算这应该工作

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 ;

测试它:

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)

这是一种黑客攻击,并且在权限不受您控制的某些数据库上将无法使用information_schema。

答案 1 :(得分:0)

您可以尝试在select语句中连接它,而不是存储自动增量列和id列,

SELECT CONCAT(id, substring(name,4) FROM tbl_employee

这样你就不需要触发器了