I have a form in which the user enters their e-mail address along with their use开发者_Python百科rname and desired password. How would I go about creating a trigger that will copy the e-mail address into the username field (located in the same row) if the user doesn't select a user name?
Table: Users +-------+---------+------+-----+---------+ | uName | uPassword | uEmail | +-------+---------+------+-----+---------+ | NULL | pass123 | uzr@sql.com | +-------+---------+------+-----+---------+
Are you sure you need a trigger to do that? If you have control over your insert or update statement (which you may not if you're using an ORM) you can do something like this:
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)
If you don't have control over the insert/update statements, then yes, you can use a trigger for that:
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)
精彩评论