简体   繁体   English

MySQL UNIQUE约束..如何解决此错误?

[英]MySQL UNIQUE constraint..How do I fix this bug?

Firstly, by using Primary key am I applying the UNIQUE constraint properly? 首先,通过使用主键,我是否可以正确地应用UNIQUE约束?

<?php
// Make a MySQL Connection
mysql_connect("localhost", "oassda", "oas53a") or die(mysql_error());
mysql_select_db("o345ja") or die(mysql_error());

// Create a MySQL table in the selected database
mysql_query("CREATE TABLE PersonInfo(
Email VARCHAR(45) NOT NULL AUTO_INCREMENT, 
PRIMARY KEY(Email),
 PNumber VARCHAR(45))")
 or die(mysql_error());  

echo "Table Created!";

?>

I am trying to make it so Email and PNumber cannot have duplicate rows inserted..But the error I get is "Incorrect column specifier for column 'Email'" apparently this is a bug due to AUTO_INCREMENT only working on INT types....Any idea what to do to make these 2 columns without duplicates ? 我正在尝试使其无法在Email和PNumber中插入重复的行。.但是我得到的错误是“列'Email'的不正确的列说明符”,显然这是由于AUTO_INCREMENT仅适用于INT类型而引起的错误。不知道该怎么做才能使这两列没有重复吗? sorry I am not experienced with MySQL too much as I did it very long time ago and new bugs have developed since then.. 抱歉,我对MySQL的了解不多,就像我很久以前一样,从那时起就出现了新的错误。

Are you looking for a composite primary key? 您在寻找复合主键吗? If so this is the code that will fix your error. 如果是这样,这是将纠正您的错误的代码。

mysql_query("CREATE TABLE PersonInfo(
Email VARCHAR(45) NOT NULL, 
 PNumber VARCHAR(45),
PRIMARY KEY(Email,PNumber))")
 or die(mysql_error());

If not you just want a primary key - the AUTO_INCREMENT flag is for INT type only . 如果不是, 则只需要主键-AUTO_INCREMENT标志仅适用于INT类型

mysql_query("CREATE TABLE PersonInfo(
    Email VARCHAR(45) NOT NULL, 
     PNumber VARCHAR(45),
    PRIMARY KEY(Email))")
     or die(mysql_error());

Or possibly you just need the UNIQUE constraint eg. 或者可能您只需要UNIQUE约束,例如。

mysql_query("CREATE TABLE PersonInfo(
        Email VARCHAR(45) NOT NULL, 
         PNumber VARCHAR(45),
        PRIMARY KEY(Email),
        UNIQUE(PNumber))")
         or die(mysql_error());
  • Yes, using Primary Key you'll have no duplicated email (you're not adding the PNumber field too) 是的,使用主键您将没有重复的电子邮件(您也不会添加PNumber字段)
  • You are using AUTO_INCREMENT on a field that is not an integer (or a sub-type like smallint). 您正在非整数字段(或类似smallint的子类型)上使用AUTO_INCREMENT
  • Take out the AUTO_INCREMENT, it's for integers and makes no sense on a field that you'll be manually populating. 取出AUTO_INCREMENT,它用于整数,并且对于将要手动填充的字段没有意义。
  • You don't need NOT NULL since primary key makes it implicit. 您不需要NOT NULL,因为主键将其隐式化。
  • Think about making your fields wider. 考虑扩大您的领域。 I have email addrs longer than 45 chars. 我的电子邮件地址超过45个字符。 (Ie, because of TMDA.) (即,因为有TMDA。)

     CREATE TABLE PersonInfo ( Email VARCHAR(45), PNumber VARCHAR(45), PRIMARY KEY (Email, PNumber) ); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM