Question

I am trying to create database tables and get them connected. I have ensured that my data types are identical. I also ensure that my tables are made before added the FK. Any advice would be greatly appreciated.

SQL query:

ALTER TABLE `Member` ADD FOREIGN KEY ( memberId ) REFERENCES `Order_Head` ( `memberId` ) ;

MySQL said: Documentation
#1005 - Can't create table 'test2.#sql-184c_63' (errno: 150) (Details...) 





-- ---
-- Table 'Order_Head'
-- 
-- ---

DROP TABLE IF EXISTS `Order_Head`;

CREATE TABLE `Order_Head` (
  `orderId` INTEGER NOT NULL AUTO_INCREMENT,
  `memberId` INTEGER NOT NULL,
  `date` DATE NOT NULL,
  PRIMARY KEY (`orderId`, `memberId`)
);

-- ---
-- Table 'Member'
-- 
-- ---

DROP TABLE IF EXISTS `Member`;

CREATE TABLE `Member` (
  `memberId` INTEGER NOT NULL AUTO_INCREMENT,
  `userName` VARCHAR(50) NOT NULL,
  `password` VARCHAR(50) NOT NULL,
  `email` VARCHAR(100) NOT NULL,
  `isAdmin` BOOLEAN NOT NULL DEFAULT false,
  PRIMARY KEY (`memberId`)
);

-- ---
-- Foreign Keys 
-- ---

ALTER TABLE `Member` ADD FOREIGN KEY (memberId) REFERENCES `Order_Head` (`memberId`);

-- ---
-- Table Properties
-- ---
ALTER TABLE `Order_Head` ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
ALTER TABLE `Member` ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
Was it helpful?

Solution

It may be because the foreign key you are trying to set up is a primary key and has AUTO_INCREMENT, maybe what you meant was:

ALTER TABLE `Order_Head` ADD FOREIGN KEY (memberId) REFERENCES `Member` (`memberId`);

Any particular reason you're not creating the foreign keys inside the CREATE TABLE statement? If not, then you should maybe do so too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top