MySQL外键引用

时间:2011-05-14 08:01:22

标签: mysql

  

可能重复:
  MySQL Foreign Key Referencing

我是新的蜜蜂我之前使用sql server 2000我的问题是在sql server 2000中创建两个表时说位置和项目表项目有一个外键引用位置表时插入值位置项目也更新了那个不需要在项目表中的外键中插入类似的值为什么我在mysql中使用insert命令在值中插入值时不可能,并且在项目上使用select命令时它不显示外键中的值请检查下面的代码

mysql> create table location(
    -> id int not null,
    -> primary key(id))
    -> engine=innodb;
Query OK, 0 rows affected (0.11 sec)


mysql> create table projects(
    -> id int,
    -> location_id int,
    -> foreign key(location_id) references location(id) on update cascade on del
ete cascade)
    -> engine=innodb;
Query OK, 0 rows affected (0.31 sec)


mysql> insert into location values('1')
Query OK, 1 row affected (0.34 sec)

mysql> select * from location;
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.00 sec)

mysql> select * from projects;
Empty set (0.00 sec)
正如你在上面的代码中看到的那样,在sql server 2000中有可能将值反映在子表中为什么在MySql中不可能为什么在两个表中都插入值是不可能在MySql中当我在位置表中插入时,项目表会自动选择值,并在我查询项目表时在选择查询中显示它

1 个答案:

答案 0 :(得分:1)

更新 - 我在重复的问题上发布了相同的答案,似乎有早期的回复。

从我在示例中看到的内容中,您没有在项目表中插入任何要执行级联更新或删除的内容。

我建议您作为一个更好的例子来演示您执行以下操作后的行为:

insert into projects values (1,1);
select * from projects;
update location set id = 2 where id = 1;
select * from projects;

您最终应该看到的是,最初插入项目行中的location_id将等于1,然后在更新位置后,项目中的location_id应更改为2.

相关问题