A
A
Artem2016-09-15 21:03:26
MySQL
Artem, 2016-09-15 21:03:26

How to avoid error when linking two mysql tables?

Hello. There are two tables.
cities
city_id - primary key
city_name
and users
id - primary keys
Name
age
city_id
You need to do this:

Data about users is stored in the users table, about cities in the cities table, the tables are interconnected by the city_id field

ALTER TABLE `users` ADD  FOREIGN KEY (`city_id`) REFERENCES `cities`(`city_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
;
MySQL response:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`livemasters`.`#sql-8f4_32c`, CONSTRAINT `#sql-8f4_32c_ibfk_1` FOREIGN KEY (`city_id`) REFERENCES `cities` ( `city_id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
What is this error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
maximw, 2016-09-15
@maximw

Probably one of the users has a city that is not in the table of cities.
You can check by query:

SELECT * FROM users AS u LEFT JOIN cities AS c ON u.city_id = c.city_id WHERE c.city_id IS NULL

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question