views:

30

answers:

2

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.

A: 

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.

Mchl
You were right just as Chris. Tnx
DixieFlatline
A: 

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)
Chris McCauley
Tnx for you querry too.
DixieFlatline
No problem, glad to help!
Chris McCauley