简体   繁体   中英

Problem with adding foreign key to table in mySql

I get error 1452 when trying to do this:

ALTER TABLE test.potovanja
ADD CONSTRAINT usr_ind
FOREIGN KEY (username) 
REFERENCES test.users (username)

(Error Code: 1452 Cannot add or update a child row: a foreign key constraint fails (test., CONSTRAINT #sql-1110_2_ibfk_1 FOREIGN KEY (username) REFERENCES users (username))). Reference key and referenced key are the same type (VARCHAR).

My SHOW CREATE TABLE outputs:

CREATE TABLE `users` (
  `username` varchar(45) NOT NULL,
  `password` varchar(45) DEFAULT NULL,
  `ime` varchar(45) DEFAULT NULL,
  `priimek` varchar(45) DEFAULT NULL,
  `nacinp` varchar(45) DEFAULT NULL,
  `email` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `potovanja` (
  `idpotovanja` int(11) NOT NULL AUTO_INCREMENT,
  `od` varchar(45) DEFAULT NULL,
  `do` varchar(45) DEFAULT NULL,
  `datumvstopa` varchar(45) DEFAULT NULL,
  `username` varchar(45) DEFAULT NULL,
  `cena` varchar(45) DEFAULT NULL,
  `datumizstopa` varchar(45) DEFAULT NULL,
  PRIMARY KEY (`idpotovanja`),
  KEY `usr_ind` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8

I really have no idea what to do.

It seems there are no rows in users table but there are some in potovanja table. This means rows in potovanja have nothing to refer to in users .

Check that all of the usernames in potovanja exist in the users table. You probably have some in potovanja that no longer exist in users

Something like this would do it ...

select * from potovanja p where not exists 
   (select * from users where users.username = p.username)

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