简体   繁体   中英

SQL foreign key constraint not failing

I have created tables for roles, users and their relation users_roles.But I am getting no error since users table is completely empty. and I can see entry in user_roles table. why this is so?

CREATE TABLE IF NOT EXISTS role
 (  
    id INT(11) NOT NULL AUTO_INCREMENT,
    roleName VARCHAR(45) DEFAULT NULL,
    PRIMARY KEY(id)

);

LOCK TABLES `role` WRITE;
ALTER TABLE `role` DISABLE KEYS ;
INSERT INTO `role` VALUES (1,'admin'),(2,'user');
ALTER TABLE `role` ENABLE KEYS ;
UNLOCK TABLES;


DROP TABLE IF EXISTS `user`;
CREATE TABLE IF NOT EXISTS `user` (
  `username` varchar(45) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;



DROP TABLE IF EXISTS `users_roles`;
CREATE TABLE `users_roles` (
  `username` varchar(45) NOT NULL REFERENCES user(username),
  `role_id` int(11) NOT NULL REFERENCES role(id),
  PRIMARY KEY (`username`,`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


insert into users_roles values (1,1);

I always created foreign keys with a slightly different syntax, I've never seen it the way you have it.

DROP TABLE IF EXISTS `users_roles`;
CREATE TABLE `users_roles` (
  `username` varchar(45) NOT NULL,
  `role_id` int(11) NOT NULL ,
 PRIMARY KEY (`username`,`role_id`),
 FOREIGN KEY(role_id) REFERENCES role(id),
 FOREIGN KEY(username) REFERENCES user(username)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

As you can see here: http://www.sqlfiddle.com/#!9/16224c , this way of creating the foreign key works.

https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html

You're missing the FOREIGN KEY in users_roles.The REFERENCES part should be on the foreign key as Dave has shown above, not on the column.

Foreign key definitions in column_definition part are ignored.

Important

[..]

MySQL parses but ignores “inline REFERENCES specifications” (as defined in the SQL standard) where the references are defined as part of the column specification. MySQL accepts REFERENCES clauses only when specified as part of a separate FOREIGN KEY specification.

Found here: reference_definition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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