我有一个表单,用户输入他们的电子邮件地址以及他们的用户名和所需的密码。如果用户没有选择用户名,我将如何创建将电子邮件地址复制到用户名字段(位于同一行)的触发器?
Table: Users +-------+---------+------+-----+---------+ | uName | uPassword | uEmail | +-------+---------+------+-----+---------+ | NULL | pass123 | uzr@sql.com | +-------+---------+------+-----+---------+
答案 0 :(得分:0)
你确定需要触发器吗?如果您可以控制插入或更新语句(如果您使用的是ORM,则可能没有),您可以执行以下操作:
mysql> insert into t4 (uemail, upassword, uname) SELECT @email:='joe@joe.com', 'secretpassword', ifnull(null, @email);
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from t4 where uemail='joe@joe.com';
+-------------+----------------+-------------+
| uname | upassword | uemail |
+-------------+----------------+-------------+
| joe@joe.com | secretpassword | joe@joe.com |
+-------------+----------------+-------------+
1 row in set (0.00 sec)
如果您无法控制insert / update语句,那么是的,您可以使用触发器:
mysql> create trigger setuname before insert on t4
-> for each row begin
-> set new.uname=ifnull(new.uname, new.uemail);
-> end;
-> |
Query OK, 0 rows affected (0.09 sec)
mysql> delimiter ;
mysql> insert into t4 (uname, uemail, upassword) values (null, 'joe@joe.com', 'secretpassword');
Query OK, 1 row affected (0.00 sec)
mysql> select * from t4;
+-------------+----------------+-------------+
| uname | upassword | uemail |
+-------------+----------------+-------------+
| joe@joe.com | secretpassword | joe@joe.com |
+-------------+----------------+-------------+
1 row in set (0.00 sec)