0

Tables:

    CREATE TABLE `relation` (
     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
     `name` varchar(40) NOT NULL,
     `gender` tinyint(1) DEFAULT NULL,
     PRIMARY KEY (`id`),
     UNIQUE KEY `unique_relation` (`name`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8

    CREATE TABLE `invite` (
     `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
     `date_sent` date NOT NULL,
     `user_id` int(10) unsigned NOT NULL,
     `relation_id` int(10) unsigned NOT NULL,
     `email` varchar(255) NOT NULL,
     `code` varchar(255) NOT NULL,
     PRIMARY KEY (`id`),
     KEY `fk_user` (`user_id`),
     CONSTRAINT `fk_user` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8

The SQL statement executed was:

ALTER TABLE `invite` 
ADD CONSTRAINT `fk_relation`  
FOREIGN KEY (`relation_id`) 
REFERENCES `relation` (`id`) 
ON DELETE CASCADE ON UPDATE RESTRICT

Mysql Error:

SQLSTATE[HY000]: General error: 1005 Can't create table 'dbtest.#sql-d00_39' (errno: 121).

The relation.id and invite.relation_id columns are of the same type int(10) unsigned

UPDATE The table invite is empty while adding this key. The table relation has 3 rows.

4

2 回答 2

1

try this :

ALTER TABLE invite
ADD CONSTRAINT fk_relation
FOREIGN KEY (relation_id)
REFERENCES relation(id)

According to the doc syntax is correct SQL FOREIGN KEY Constraint

于 2013-07-04T14:07:42.207 回答
0

The DDL for Foreign Key creation now automatically includes statements to specify actions on "Delete" and "Update". However, for "Delete", it includes the statement "ON DELETE RESTRICT", which does not appear to be a valid T-SQL statement.

TRY THIS :

ALTER TABLE invite WITH CHECK ADD CONSTRAINT fk_relation FOREIGN KEY (relation_id) REFERENCES relation (id)

于 2013-07-04T14:41:40.530 回答