插入前触发器的语法

时间:2012-07-28 23:04:03

标签: mysql triggers schema constraints mysql-error-1170

好的,所以我see这是错误的做法:

mysql> 
mysql> show tables;
+---------------------+
| Tables_in_nntp      |
+---------------------+
| articles            |
| newsgroups          |
| newsgroups_articles |
+---------------------+
3 rows in set (0.00 sec)

mysql> describe newsgroups;
+-----------+----------+------+-----+---------+----------------+
| Field     | Type     | Null | Key | Default | Extra          |
+-----------+----------+------+-----+---------+----------------+
| id        | int(11)  | NO   | PRI | NULL    | auto_increment |
| newsgroup | longtext | NO   |     | NULL    |                |
+-----------+----------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> show create table newsgroups;
+------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table      | Create Table                                                                                                                                                                      |
+------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| newsgroups | CREATE TABLE `newsgroups` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `newsgroup` longtext NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1 |
+------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE newsgroups ADD UNIQUE (newsgroup);
ERROR 1170 (42000): BLOB/TEXT column 'newsgroup' used in key specification without a key length
mysql> 

应该使用trigger填充?

好吧,作为root,我做了一个触发器:

mysql> 
mysql> show tables;
+---------------------+
| Tables_in_nntp      |
+---------------------+
| articles            |
| newsgroups          |
| newsgroups_articles |
+---------------------+
3 rows in set (0.00 sec)

mysql> 
mysql> delimiter |
mysql> CREATE TRIGGER make_hash BEFORE INSERT ON newsgroups
    ->   FOR EACH ROW BEGIN
    ->       INSERT INTO hash values ('0');
    ->   END;
    -> |
Query OK, 0 rows affected (0.18 sec)

mysql> 

然而,这只是虚拟数据。如何让触发器实际创建哈希?

1 个答案:

答案 0 :(得分:1)

我认为你应该按原样保留主键 您可以添加哈希列

ALTER TABLE `newsgroups` ADD COLUMN `hash` CHAR(32) NOT NULL DEFAULT '';

然后用

填充它
UPDATE newsgroups SET hash = MD5(newsgroup);

然后删除重复项并添加您的唯一约束。

您还可以添加BEFORE INSERTBEFORE UPDATE触发器来设置hash

CREATE DEFINER=`root`@`localhost` 
TRIGGER `before_insert_newsgroups` 
BEFORE INSERT ON `newsgroups` 
FOR EACH ROW BEGIN

    set new.hash = md5(new.newsgroup);

END

根据您使用的SQL客户端,您可能不会change the DELIMITER before and after the create trigger statement