0

好的,所以我看到这是错误的方法:

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> 

has 应该填充触发器吗?

好的,作为 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> 

但是,这只是虚拟数据。如何使该触发器实际创建哈希?

4

1 回答 1

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 客户端,您可能不想在创建触发器语句之前和之后更改 DELIMITER

于 2012-07-28T23:15:04.850 回答