如何使mysql字段独一无二?

时间:2012-03-02 03:29:27

标签: mysql field unique

有没有办法让现有的txt字段唯一(不接受重复的值)?

字段:post_title
输入:文字
整理:utf8_unicode_ci
空:辛
默认值:NULL

如果有人试图插入包含现有标题的帖子,会发生什么?

这会影响我网站的某些功能吗?

结构

CREATE TABLE IF NOT EXISTS `hotaru_posts` (
  `post_id` int(20) NOT NULL AUTO_INCREMENT,
  `post_archived` enum('Y','N') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'N',
  `post_updatedts` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `post_author` int(20) NOT NULL DEFAULT '0',
  `post_date` timestamp NULL DEFAULT NULL,
  `post_pub_date` timestamp NULL DEFAULT NULL,
  `post_status` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'processing',
  `post_type` varchar(32) COLLATE utf8_unicode_ci DEFAULT NULL,
  `post_category` int(20) NOT NULL DEFAULT '1',
  `post_tags` text COLLATE utf8_unicode_ci,
  `post_title` text COLLATE utf8_unicode_ci,
  `post_orig_url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `post_domain` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `post_url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `post_content` text COLLATE utf8_unicode_ci,
  `post_votes_up` smallint(11) NOT NULL DEFAULT '0',
  `post_votes_down` smallint(11) NOT NULL DEFAULT '0',
  `post_comments` enum('open','closed') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'open',
  `post_media` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'text',
  `post_img` text COLLATE utf8_unicode_ci NOT NULL,
  `post_subscribe` tinyint(1) NOT NULL DEFAULT '0',
  `post_updateby` int(20) NOT NULL DEFAULT '0',
  `post_views` int(20) NOT NULL DEFAULT '0',
  `post_last_viewer_ip` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT '111.111.111.111',
  PRIMARY KEY (`post_id`),
  KEY `post_archived` (`post_archived`),
  KEY `post_status` (`post_status`),
  KEY `post_type` (`post_type`),
  FULLTEXT KEY `post_title` (`post_title`,`post_domain`,`post_url`,`post_content`,`post_tags`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Story Posts' AUTO_INCREMENT=38275 ;

3 个答案:

答案 0 :(得分:4)

这里发生错误是因为MySQL只能索引BLOB或TEXT列的前N个字符。因此,当存在字段/列类型的TEXT或BLOB或者属于TEXT或BLOB类型(例如TINYBLOB,MEDIUMBLOB,LONGBLOB,TINYTEXT,MEDIUMTEXT和LONGTEXT)时,错误主要发生在您尝试将其作为主键或索引。对于没有长度值的完整BLOB或TEXT,MySQL无法保证列的唯一性 它具有可变和动态的大小。因此,当使用BLOB或TEXT类型作为索引时,必须提供N的值,以便MySQL可以确定密钥长度。但是,MySQL不支持对TEXT或BLOB的限制。文本(88)根本不起作用。

所以解决方案是删除TEXT并设置为长度为255的VARCHAR数据类型。(默认为长度)。

`post_title` varchar(255) COLLATE utf8_unicode_ci UNIQUE KEY

答案 1 :(得分:0)

试试这个:

ALTER TABLE tableName   
  ADD  UNIQUE INDEX `post_title_Index` (`post_title`);

答案 2 :(得分:0)

我认为你需要在post_title字段中添加一个长度。给它一些数字,这应该解决错误。

ALTER TABLE `hotaru_posts` 
  ADD  UNIQUE INDEX `post_title_Index` (`post_title`,`value`(255));

试一试。