开发者

MySQL Foreign Key Referencing

I m a new bee i have used sql server 2000 before my question is when creating two tables in sql server 2000 say location and projects table projects having a foreign key referencing the location table when inserting values in location the projects is also updated thats is no need to insert the similar value in the foreign key in projects table why is it not possible in mysql when i insert values in location开发者_开发技巧 using insert command and when using select command on projects it does not shows the value in foreign key please check the below code

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)

as u see in the above code it was possible in sql server 2000 that the value was reflected in the child table why is it not possible in MySql Why should the value be insert in both the tables isn't it possible in MySql that when i insert in the location table the projects table pick the value automatically and show it in select Query when i query the projects table


From what I can see in the example, you haven't inserted anything in the projects table in which to have a cascaded update or delete performed.

I would suggest as a better example to demonstrate the behaviour you're after that you perform the following, after doing the steps above:

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

What you should end up seeing, is that initially the location_id in the inserted projects row will be equal to 1, then after the update of location, the location_id in projects should change to 2. This demonstrates that the change to the id of the location table has cascaded to update the location_id field of the row in the projects table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜