Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mysql code give me foreign key is incorrectly formed

I want to create a small database but I get everytime an error:

here is mysql code:

DROP TABLE IF EXISTS `orders`;

CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `customer` varchar(25) NOT NULL DEFAULT '',
  `address1` varchar(100) DEFAULT NULL,
  `city` varchar(25) NOT NULL DEFAULT '',
  `postcode` varchar(25) NOT NULL DEFAULT '',
  `country` varchar(25) NOT NULL DEFAULT '',
  `amount` varchar(11) NOT NULL DEFAULT '',
  `status` varchar(10) NOT NULL DEFAULT '',
  `deleted` varchar(10) NOT NULL DEFAULT '',
  `date` datetime NOT NULL,
  `last_modified` datetime DEFAULT NULL,
  `customers_id` int(11) NOT NULL,
  PRIMARY KEY (id),
  CONSTRAINT orders_customers_id_fk FOREIGN KEY (customers_id) 
     REFERENCES customers (id)  ON DELETE SET NULL);
  
LOCK TABLES `orders` WRITE;
/*!40000 ALTER TABLE `orders` DISABLE KEYS */;


/*!40000 ALTER TABLE `orders` ENABLE KEYS */;
UNLOCK TABLES;


# Dump of table customers
# ------------------------------------------------------------

DROP TABLE IF EXISTS `customers`;

CREATE TABLE `customers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `role` varchar(25) NOT NULL DEFAULT '',
  `name` varchar(50) NOT NULL DEFAULT '',
  `surname` varchar(50) NOT NULL DEFAULT '',
  `email` varchar(50) NOT NULL DEFAULT '',
  `password` char(255) NOT NULL DEFAULT '',
  `created_at` datetime NOT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

I tried syntax of foreign key code but with the same error I don’t know why?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I get this error :

#1005 - Can't create table `management`.`orders` (errno: 150 "Foreign key constraint is incorrectly formed")

>Solution :

To declare a foreign key constraint the table to which this key is defined must already exist.

In this case you’re trying to link to a table that doesn’t exist, so you’ll need to re-order the CREATE TABLE statements accordingly.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading