MySQL:特定引用的问题

标签 mysql reference innodb

我有两张 table 。上面是一个包含 IP 范围及其各自国家/地区属性的表(IPGEO 表)。另一个是一个表,它仅跟踪每个用户访问该网站的最后一个国家/地区。我们的想法是,如果用户突然从另一个国家/地区访问该网站,我会通过电子邮件通知用户。

现在来看看实际的表格。我有这两个:

包含 IP 范围的 IPGeo 表

CREATE  TABLE IF NOT EXISTS `politiker_lu`.`IPGeo` (
  `IPFrom` INT(11) NOT NULL ,
  `IPTo` INT(11) NOT NULL ,
  `code2` VARCHAR(2) NOT NULL ,
  `code3` VARCHAR(3) NOT NULL ,
  `Country` VARCHAR(45) NOT NULL ,
  INDEX `index1` (`IPFrom` ASC) ,
  INDEX `index2` (`IPTo` ASC) )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

然后,user_geo 表跟踪用户访问网站的最后一个国家/地区。

CREATE  TABLE IF NOT EXISTS `politiker_lu`.`user_geo` (
  `fi_user` INT(10) UNSIGNED NOT NULL ,
  `fi_country` VARCHAR(3) NOT NULL ,
  `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ,
  PRIMARY KEY (`fi_user`) ,
  INDEX `fk_user_geo_1` (`fi_user` ASC) ,
  CONSTRAINT `fk_user_geo_1`
    FOREIGN KEY (`fi_user` )
    REFERENCES `politiker_lu`.`user` (`id_user` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

这些是现有的表格。我现在想引用这两个表,如下所示:

ALTER TABLE `politiker_lu`.`user_geo` 
  ADD CONSTRAINT `fk_user_geo_IPGeo1`
  FOREIGN KEY (`fi_country` )
  REFERENCES `politiker_lu`.`IPGeo` (`code3` )
  ON DELETE CASCADE
  ON UPDATE CASCADE
, ADD INDEX `fk_user_geo_IPGeo1` (`fi_country` ASC) ;

但是该语句失败,错误代码为 150。两个表都是 utf8,两个列具有相同的数据类型。我在这里错过了一些重要的东西吗?

注释

user存在并具有所有引用,实际上与问题无关。我保留它是为了不需要对语句进行太多编辑。

最佳答案

您需要在 IPGeo.code3 列上添加唯一索引或主键,以便使用外键引用它。

您可以通过运行 show engine innodb status\G 并查看LATEST FOREIGN KEY ERROR 部分来查看该错误。该错误可能如下所示:

Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html
for correct foreign key definition.

关于MySQL:特定引用的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4450251/

相关文章:

php - 如何防止 php 或 mysql 级别的双重表单提交?

php - 查询延迟返回一篇文章

MYSQL Count group by rows 忽略 JOIN 和 SUM 字段对 Joined 表的影响

MySQL InnoDB 解锁一行

php - mysql_fetch_array 不会遍历所有结果

c++ - 返回对结构的引用

java - 引用数组引发与扫描仪有关的错误

c# - Xamarin.Android nuget 包引用 System.Web

mysql - Innodb 和 MyISAM 表问题

mysql - 如何锁定 MySQL 表以防止更新,直到执行两个单独的 select 语句