ERROR 1005 (HY000) errno: 150 - mysql-error-1005

I am having this problem, which has been addressed in many posts, but none of them show where I am going wrong. I get the error 1005 with errno 150 when I try the following;
structure of appointments:
CREATE TABLE `appointments` (
`appointmentID` int(11) NOT NULL AUTO_INCREMENT,
`apptNum` tinyint(3) unsigned NOT NULL DEFAULT '1',
`cwaID` int(11) NOT NULL DEFAULT '0',
`siteID` int(11) DEFAULT NULL,
`titleCode` varchar(25) NOT NULL,
`apptPercentage` double DEFAULT '0',
`status` varchar(2) CHARACTER SET utf8 DEFAULT NULL,
`payRate` double DEFAULT '0',
`rateCode` varchar(5) CHARACTER SET utf8 DEFAULT NULL,
`locationInfo` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
`apptStartDate` date DEFAULT NULL,
`apptEndDate` date DEFAULT NULL,
`isPrimaryAppointment` varchar(1) CHARACTER SET utf8 NOT NULL
DEFAULT 'y',
`lastModDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE
CURRENT_TIMESTAMP,
PRIMARY KEY (`appointmentID`),
UNIQUE KEY `appointmentID` (`appointmentID`),
UNIQUE KEY `cwaID-apptNum` (`cwaID`,`apptNum`),
KEY `apptNum` (`apptNum`),
KEY `siteID` (`siteID`),
KEY `rateCode` (`rateCode`),
KEY `cwaID` (`cwaID`),
KEY `titleCode` (`titleCode`),
CONSTRAINT `FK_employees_appointments` FOREIGN KEY (`cwaID`) REFERENCES
`employees` (`cwaID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
structure of jobtitles:
CREATE TABLE `jobtitles` (
`titleCode` varchar(25) CHARACTER SET utf8 NOT NULL,
`jobTitle` varchar(255) CHARACTER SET utf8 NOT NULL,
`unitID` varchar(10) CHARACTER SET utf8 NOT NULL,
`scope` varchar(10) CHARACTER SET utf8 NOT NULL,
`payPeriod` char(1) NOT NULL DEFAULT 'M',
`maxPay` decimal(8,2) NOT NULL DEFAULT '0.00',
`minPay` decimal(8,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (`titleCode`),
KEY `jobTitle` (`jobTitle`),
KEY `scope` (`scope`),
KEY `unitID` (`unitID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
I want to add a foreign key to appointments for the titleCode field:
ALTER TABLE appointments ADD CONSTRAINT `FK_jobtitles_appointments`
FOREIGN KEY (`titleCode`) REFERENCES `jobtitles` (`titleCode`);
but this attempt generates the ERROR 1005 with errno 150, which implies a badly formed foreign key.
Any suggestions?

Related

how to optimize this query further more

I tried all i could do but could not get the least execution time.
SELECT e.code_assigned,
Count(DISTINCT tcp.id) AS total_qa,
Count(DISTINCT tcp.encounter_uid) AS total_records,
Sum(IF(tcp.qa_disagree = '1', tcd.weight, 0)) AS error_points,
Sum(IF(tcp.qa_disagree = '1',1,0)) AS total_disagree,
Sum(tcd.weight) AS total_qa_weight,
Count(DISTINCT CASE WHEN tcp.qa_disagree = '1' THEN tcp.encounter_uid end) AS total_disagree_record
FROM tbl_encounter_detail AS e
STRAIGHT_JOIN tbl_event_cpt_pro AS tcp ON tcp.encounter_uid = e.encounter_uid AND tcp.work_item_uid = e.work_item_uid
JOIN tbl_encounter as ed ON tcp.encounter_uid = ed.encounter_uid
LEFT JOIN tbl_code_weight AS tcd ON tcd.code = tcp.procedure_num
WHERE e.qa_complete = 1
GROUP BY code_assigned
UNION ALL
SELECT e.code_assigned,
Count(DISTINCT tcf.id) AS total_qa,
Count(DISTINCT tcf.encounter_uid) AS total_records,
Sum(IF(tcf.qa_disagree = '1', tcd.weight, 0)) AS error_points,
Sum(IF(tcf.qa_disagree = '1',1,0)) AS total_disagree,
Sum(tcd.weight) AS total_qa_weight,
Count(DISTINCT CASE WHEN tcf.qa_disagree = '1' THEN tcf.encounter_uid end) AS total_disagree_record
FROM tbl_encounter_detail AS e
STRAIGHT_JOIN tbl_event_cpt_fac AS tcf ON tcf.encounter_uid = e.encounter_uid AND tcf.work_item_uid = e.work_item_uid
JOIN tbl_encounter as ed ON tcf.encounter_uid = ed.encounter_uid
LEFT JOIN tbl_code_weight AS tcd ON tcd.code = tcf.procedure_num
WHERE e.qa_complete = 1
GROUP BY code_assigned
This query is hampering performance (this is the least that i am able to do) I don't know why am i not able to optimize it more. what is really hampering it? Please help.
new explain plan
for tbl_event_cpt_pro and tbl_event_cpt_fac
CREATE TABLE `tbl_event_cpt_pro` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`encounter_uid` int(11) NOT NULL,
`procedure_num` varchar(10) NOT NULL,
`procedure_qty` int(11) NOT NULL DEFAULT '1',
`procedure_modifier1` varchar(10) DEFAULT NULL,
`procedure_modifier2` varchar(10) DEFAULT NULL,
`procedure_provider` varchar(75) DEFAULT NULL,
`mid_provider` varchar(75) DEFAULT NULL,
`userid` varchar(50) NOT NULL,
`user_time_entered` datetime NOT NULL,
`qa_disagree` tinyint(1) NOT NULL DEFAULT '0',
`qa_procedure_num` varchar(10) DEFAULT NULL,
`qa_procedure_qty` int(5) DEFAULT NULL,
`qa_procedure_modifier` varchar(10) DEFAULT NULL,
`qa_procedure_provider` varchar(75) DEFAULT NULL,
`qa_note` varchar(255) DEFAULT NULL,
`qa_userid` varchar(50) DEFAULT NULL,
`qa_user_time_entered` datetime DEFAULT NULL,
`qa_reason` varchar(75) DEFAULT NULL,
`work_item_uid` int(11) NOT NULL,
`user_time_entered_utc` datetime DEFAULT NULL,
`cosigning_physician` varchar(75) DEFAULT NULL,
`procedure_date` date DEFAULT NULL COMMENT 'Date procedure was
performed. May not be date of service/admit date.',
`charge_code_select` varchar(20) DEFAULT NULL COMMENT 'If the
procedure CPT has multiple charge codes, this indicates the one chosen by coder',
`specialist` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Indicates Specialist outpatient procedure - ref IU and Sturdy',
`dos` date DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_enc_uid` (`encounter_uid`),
KEY `procedure_provider` (`procedure_provider`),
KEY `mid_provider` (`mid_provider`),
KEY `qa_procedure_provider` (`qa_procedure_provider`),
KEY `userid` (`userid`),
KEY `qa_userid` (`qa_userid`),
KEY `work_item_uid` (`work_item_uid`),
KEY `work_item_uid_2` (`work_item_uid`,`encounter_uid`),
KEY `cosigning_physician` (`cosigning_physician`),
KEY `code_index` (`procedure_num`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_1` FOREIGN KEY (`encounter_uid`) REFERENCES `tbl_encounter` (`encounter_uid`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_10` FOREIGN KEY (`work_item_uid`) REFERENCES `tbl_work_item` (`work_item_uid`) ON DELETE CASCADE,
CONSTRAINT `tbl_event_cpt_pro_ibfk_11` FOREIGN KEY (`userid`) REFERENCES `tbl_user` (`user_email_address`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_12` FOREIGN KEY (`work_item_uid`, `encounter_uid`) REFERENCES `tbl_encounter_detail` (`work_item_uid`, `encounter_uid`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_13` FOREIGN KEY (`cosigning_physician`) REFERENCES `tbl_provider` (`provider_lov`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_2` FOREIGN KEY (`procedure_provider`) REFERENCES `tbl_provider` (`provider_lov`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_3` FOREIGN KEY (`mid_provider`) REFERENCES `tbl_provider` (`provider_lov`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_4` FOREIGN KEY (`qa_procedure_provider`) REFERENCES `tbl_provider` (`provider_lov`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_5` FOREIGN KEY (`userid`) REFERENCES `tbl_user` (`user_email_address`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_6` FOREIGN KEY (`qa_userid`) REFERENCES `tbl_user` (`user_email_address`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_7` FOREIGN KEY (`work_item_uid`) REFERENCES `tbl_work_item` (`work_item_uid`),
CONSTRAINT `tbl_event_cpt_pro_ibfk_9` FOREIGN KEY (`encounter_uid`) REFERENCES `tbl_encounter` (`encounter_uid`) ON DELETE CASCADE
)
for tbl_encounter_detail
CREATE TABLE `tbl_encounter_detail` (
`enc_detail_uid` int(11) NOT NULL AUTO_INCREMENT,
`encounter_uid` int(11) NOT NULL,
`work_item_uid` int(11) NOT NULL,
`code_assigned` varchar(50) DEFAULT NULL,
`coding_start_time` datetime DEFAULT NULL,
`code_complete_ts` datetime DEFAULT NULL,
`code_complete` int(1) NOT NULL DEFAULT '0',
`suspend_active` int(1) DEFAULT NULL,
`qa_flag` int(1) NOT NULL DEFAULT '0',
`qa_complete` int(1) NOT NULL DEFAULT '0',
`qa_start_time` datetime DEFAULT NULL,
`qa_complete_ts` datetime DEFAULT NULL,
`qa_assigned` varchar(50) DEFAULT NULL,
`dataentry_complete` int(1) NOT NULL DEFAULT '0',
`dataentry_start_time` datetime DEFAULT NULL,
`dataentry_complete_ts` datetime DEFAULT NULL,
`dataentry_assigned` varchar(50) DEFAULT NULL,
`encounter_status` varchar(30) NOT NULL,
`dataentry_assigned_tec` varchar(50) DEFAULT NULL COMMENT 'Data entry user for Technical component',
`dataentry_complete_tec` int(1) NOT NULL DEFAULT '0' COMMENT 'Data Entry complete for Technical component; used only for split data entry clients',
`dataentry_assigned_pf` varchar(50) DEFAULT NULL COMMENT 'Data entry user for Profee component',
`dataentry_complete_pf` int(1) NOT NULL DEFAULT '0' COMMENT 'Data Entry complete for Profee component',
`qa_feedback` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Set when the QA reviewer has feedback on disagreements',
`qa_seen_by_coder_utc` datetime DEFAULT NULL COMMENT 'Set when the coder acknowledges QA feedback on this encounter',
`qa_dataentry` tinyint(1) DEFAULT '0' COMMENT 'Set if data entry requested QA',
`code_complete_pf` tinyint(1) DEFAULT '0' COMMENT 'When LiveCode and split data entry are active, this indicates Profee coding is done; otherwise ignored',
`qa_requested` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Whether QA was requested by Coder or Data Entry (vs random sample)',
PRIMARY KEY (`enc_detail_uid`),
UNIQUE KEY `uniq_wi_enc` (`work_item_uid`,`encounter_uid`),
KEY `idx_enc_uid` (`encounter_uid`),
KEY `idx_code_assigned` (`code_assigned`),
KEY `encounter_status` (`encounter_status`),
KEY `qa_assigned` (`qa_assigned`),
KEY `dataentry_assigned` (`dataentry_assigned`),
KEY `dataentry_assigned_tec` (`dataentry_assigned_tec`),
KEY `dataentry_assigned_pf` (`dataentry_assigned_pf`),
KEY `idx_qa_complete` (`qa_complete`),
KEY `idx_composite` (`qa_complete`,`code_assigned`,`encounter_uid`,`work_item_uid`),
CONSTRAINT `tbl_encounter_detail_ibfk_1` FOREIGN KEY (`encounter_uid`) REFERENCES `tbl_encounter` (`encounter_uid`),
CONSTRAINT `tbl_encounter_detail_ibfk_2` FOREIGN KEY (`work_item_uid`) REFERENCES `tbl_work_item` (`work_item_uid`),
CONSTRAINT `tbl_encounter_detail_ibfk_3` FOREIGN KEY (`code_assigned`) REFERENCES `tbl_user` (`user_email_address`),
CONSTRAINT `tbl_encounter_detail_ibfk_4` FOREIGN KEY (`qa_assigned`) REFERENCES `tbl_user` (`user_email_address`),
CONSTRAINT `tbl_encounter_detail_ibfk_5` FOREIGN KEY (`dataentry_assigned`) REFERENCES `tbl_user` (`user_email_address`),
CONSTRAINT `tbl_encounter_detail_ibfk_6` FOREIGN KEY (`dataentry_assigned_tec`) REFERENCES `tbl_user` (`user_email_address`),
CONSTRAINT `tbl_encounter_detail_ibfk_7` FOREIGN KEY (`dataentry_assigned_pf`) REFERENCES `tbl_user` (`user_email_address`),
CONSTRAINT `tbl_encounter_detail_ibfk_8` FOREIGN KEY (`encounter_status`) REFERENCES `tbl_encounter_status` (`id`)
)
for tbl_encounter
CREATE TABLE `tbl_encounter` (
`encounter_uid` int(11) NOT NULL AUTO_INCREMENT,
`patient_name` varchar(75) NOT NULL,
`patient_sex` varchar(1) NOT NULL,
`patient_dob` date NOT NULL,
`encounter_dos` date NOT NULL,
`batch_control` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_location` varchar(50) CHARACTER SET latin1 DEFAULT NULL,
`facility_id` varchar(75) NOT NULL,
`patient_mrn` varchar(20) NOT NULL,
`patient_fin` varchar(20) NOT NULL,
`encounter_lwbs` tinyint(1) DEFAULT NULL,
`encounter_ama` tinyint(1) DEFAULT NULL,
`encounter_reason_for_visit` varchar(300) DEFAULT NULL,
`encounter_chief_complaint` varchar(2048) DEFAULT NULL,
`encounter_ins_type` varchar(50) CHARACTER SET latin1 DEFAULT NULL,
`encounter_ins_1` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_ins_2` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_primary_type` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_primary_class` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_secondary_type` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_secondary_class` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_disch_diagnosis` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_disch_disp` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_type` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_assign_provider1` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`encounter_assign_provider2` varchar(75) DEFAULT NULL COMMENT 'Obsolete - should be dropped in future',
`encounter_admit_mode` varchar(75) CHARACTER SET latin1 DEFAULT NULL,
`load_time` datetime NOT NULL,
`enc_admit` datetime DEFAULT NULL COMMENT 'Datetime of inpatient admission.',
`import_loc` varchar(200) DEFAULT NULL COMMENT 'Source of record: typically file name and line number',
`import_line` bigint(20) unsigned DEFAULT NULL,
`attend_provider_uid` int(10) unsigned DEFAULT NULL,
`disch_time_utc` datetime DEFAULT NULL,
`last_adt_recorded_utc` datetime DEFAULT NULL COMMENT 'The EVN.2 recorded timestamp of the last ADT update applied. Used to ensure updates are applied in order.',
`loaded_disch_disp` varchar(75) DEFAULT NULL COMMENT 'The discharge disposition originally loaded from ED Log for this chart',
`admitted` tinyint(1) DEFAULT NULL,
`injury_real_date` date DEFAULT NULL,
`lmp_date` date DEFAULT NULL COMMENT 'Last Menstrual Period',
`transfer` tinyint(1) DEFAULT NULL COMMENT 'Coded in patient header when patient was transferred between facilities',
`transfer_dest` varchar(75) DEFAULT NULL COMMENT 'If chart is a transfer to another facility, the coder specifies the facility in this field',
`dos_end` date DEFAULT NULL,
`outpatient` tinyint(1) DEFAULT NULL,
`discharge` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`encounter_uid`),
KEY `idx_fac_id` (`facility_id`),
KEY `idx_name` (`patient_name`),
KEY `idx_dos` (`encounter_dos`),
KEY `attend_provider_uid` (`attend_provider_uid`),
KEY `idx_fin` (`patient_fin`),
KEY `idx_ins` (`encounter_primary_type`),
KEY `idx_prov` (`encounter_assign_provider1`),
KEY `idx_mrn_temp` (`patient_mrn`),
CONSTRAINT `tbl_encounter_ibfk_1` FOREIGN KEY (`attend_provider_uid`) REFERENCES `tbl_provider` (`provider_uid`)
)
for tbl_code_weight
Create Table: CREATE TABLE `tbl_code_weight` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`code` varchar(20) NOT NULL,
`weight` float NOT NULL,
KEY `idx_composite` (`code`,`weight`)
PRIMARY KEY (`id`)
)

1215 - Cannot add foreign key constraint

I actualy try to create a database but i have an error with the foreign key. Can you hepl me please ?
DROP TABLE IF EXISTS `City`;
CREATE TABLE `City` (`id` int(11) NOT NULL AUTO_INCREMENT,
`idCountry` int(11) DEFAULT NULL,
`Name` char(35) CHARACTER SET latin1 NOT NULL DEFAULT '',
`CountryCode` char(3) CHARACTER SET latin1 NOT NULL DEFAULT '',
`District` char(20) CHARACTER SET latin1 NOT NULL DEFAULT '',
`Population` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`) USING BTREE,
KEY `fk_constraint_city_country` (`idCountry`),
CONSTRAINT `fk_constraint_city_country` FOREIGN KEY (`idCountry`)
REFERENCES `Country` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4080 DEFAULT CHARSET=utf8;
I have this error: MySQL said: Documentation
1215 - Cannot add foreign key constraint
DROP TABLE IF EXISTS `Country`;
CREATE TABLE `Country` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Code` char(3) CHARACTER SET latin1 DEFAULT NULL,
`Name` char(52) CHARACTER SET latin1 NOT NULL DEFAULT '',
`Continent` enum('Asia','Europe','North
America','Africa','Oceania','Antarctica','South America') CHARACTER SET
latin1 NOT NULL DEFAULT 'Asia',
`Region` char(26) CHARACTER SET latin1 NOT NULL DEFAULT '',
`SurfaceArea` float(10,2) NOT NULL DEFAULT '0.00',
`IndepYear` smallint(6) DEFAULT NULL,
`Population` int(11) NOT NULL DEFAULT '0',
`LifeExpectancy` float(3,1) DEFAULT NULL,
`GNP` float(10,2) DEFAULT NULL,
`GNPOld` float(10,2) DEFAULT NULL,
`LocalName` char(45) CHARACTER SET latin1 NOT NULL DEFAULT '',
`GovernmentForm` char(45) CHARACTER SET latin1 NOT NULL DEFAULT '',
`HeadOfState` char(60) CHARACTER SET latin1 DEFAULT NULL,
`Capital` int(11) DEFAULT NULL,
`Code2` char(2) CHARACTER SET latin1 NOT NULL DEFAULT '',
PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=240 DEFAULT CHARSET=utf8;
and there is the country langage:
DROP TABLE IF EXISTS `CountryLanguage`;
CREATE TABLE `CountryLanguage` (
`idCountry` int(11) NOT NULL DEFAULT '0',
`idLanguage` int(11) NOT NULL DEFAULT '0',
`IsOfficial` enum('T','F') CHARACTER SET latin1 NOT NULL DEFAULT 'F',
`Percentage` float(4,1) NOT NULL DEFAULT '0.0',
PRIMARY KEY (`idCountry`,`idLanguage`) USING BTREE,
KEY `fk_constraint_Language` (`idLanguage`),
CONSTRAINT `fk_constraint_Country` FOREIGN KEY (`idCountry`) REFERENCES
`Country` (`id`),
CONSTRAINT `fk_constraint_Language` FOREIGN KEY (`idLanguage`)
REFERENCES `Language` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf

MySQL - Why can't I add a foreign key here?

I'm not sure why I'm not able to add a particular foreign key here. These tables were generated via MySQL Workbench, and based on the MySQL documentation and on searching for other similar problems / solutions, I think everything is in order...yet I can't add one foreign key in particular:
inspection_statuses.inspection_id needs to reference inspection_responses.tpa_result
What am I missing / overlooking?
This is the statement I'm trying to use to add the new foreign key:
ALTER TABLE `vipsouth_app`.`inspection_statuses`
ADD CONSTRAINT `inspection_statuses_ibfk_3`
FOREIGN KEY (`inspection_id`)
REFERENCES `vipsouth_app`.`inspection_responses` (`tpa_result`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
And that produces this error:
Operation failed: There was an error while applying the SQL script to the database.
ERROR 1005: Can't create table vipsouth_app.#sql-1f48_7 (errno: 150 "Foreign key constraint is incorrectly formed")
CREATE TABLE `inspection_responses` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`inspection_request_id` int(10) unsigned NOT NULL,
`tpa_result` varchar(10) CHARACTER SET utf8 NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`created_by` int(10) unsigned NOT NULL DEFAULT '0',
`updated_at` timestamp NULL DEFAULT NULL,
`updated_by` int(10) unsigned DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`deleted_by` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
UNIQUE KEY `tpa_result_UNIQUE` (`tpa_result`),
KEY `inspection_responses_ibfk_1_idx` (`inspection_request_id`),
CONSTRAINT `inspection_responses_ibfk_1` FOREIGN KEY (`inspection_request_id`) REFERENCES `inspection_requests` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
CREATE TABLE `inspection_statuses` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`inspection_request_id` int(10) unsigned NOT NULL,
`inspection_response_id` int(10) unsigned NOT NULL,
`tpa_code` varchar(4) COLLATE utf8_unicode_ci NOT NULL,
`user_id` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`inspection_id` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`status` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`note` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL,
`url` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`created_by` int(10) unsigned NOT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`updated_by` int(10) unsigned DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`deleted_by` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `inspection_statuses_ibfk_1_idx` (`inspection_request_id`),
KEY `inspection_statuses_ibfk_2_idx` (`inspection_response_id`),
CONSTRAINT `inspection_statuses_ibfk_1` FOREIGN KEY (`inspection_request_id`) REFERENCES `inspection_requests` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `inspection_statuses_ibfk_2` FOREIGN KEY (`inspection_response_id`) REFERENCES `inspection_responses` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
The data types and constraints defined on both the columns should be exactly the same. Except for a foreign key can be NULLable.
This should do it for you. I did not get any error.
SET foreign_key_checks = 0;
CREATE TABLE `inspection_responses` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`inspection_request_id` int(10) unsigned NOT NULL,
`tpa_result` varchar(10) CHARACTER SET utf8 NOT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`created_by` int(10) unsigned NOT NULL DEFAULT '0',
`updated_at` timestamp NULL DEFAULT NULL,
`updated_by` int(10) unsigned DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`deleted_by` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
UNIQUE KEY `tpa_result_UNIQUE` (`tpa_result`),
KEY `inspection_responses_ibfk_1_idx` (`inspection_request_id`),
CONSTRAINT `inspection_responses_ibfk_1` FOREIGN KEY (`inspection_request_id`) REFERENCES `inspection_requests` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `inspection_statuses` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`inspection_request_id` int(10) unsigned NOT NULL,
`inspection_response_id` int(10) unsigned NOT NULL,
`tpa_code` varchar(4) COLLATE utf8_unicode_ci NOT NULL,
`user_id` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`password` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`inspection_id` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`status` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`note` varchar(1000) COLLATE utf8_unicode_ci DEFAULT NULL,
`url` varchar(1024) COLLATE utf8_unicode_ci DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`created_by` int(10) unsigned NOT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`updated_by` int(10) unsigned DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`deleted_by` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `inspection_statuses_ibfk_1_idx` (`inspection_request_id`),
KEY `inspection_statuses_ibfk_2_idx` (`inspection_response_id`),
CONSTRAINT `inspection_statuses_ibfk_1` FOREIGN KEY (`inspection_request_id`) REFERENCES `inspection_requests` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `inspection_statuses_ibfk_2` FOREIGN KEY (`inspection_response_id`) REFERENCES `inspection_responses` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
SET foreign_key_checks = 1;

Foreign ID in SQL tables to link one table to another

This is my SQL code which links users to items based on tutorials:
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`user_password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`user_email` varchar(254) COLLATE utf8_unicode_ci NOT NULL,
`user_access_level` tinyint(3) unsigned NOT NULL DEFAULT '0',
`user_active` tinyint(1) NOT NULL DEFAULT '0',
`user_activation_hash` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`user_password_reset_hash` char(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`user_password_reset_timestamp` bigint(20) DEFAULT NULL,
`user_failed_logins` tinyint(1) NOT NULL DEFAULT '0',
`user_last_failed_login` int(10) DEFAULT NULL,
`user_registration_datetime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`user_registration_ip` varchar(39) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0.0.0.0',
PRIMARY KEY (`user_id`),
UNIQUE KEY `user_name` (`user_name`),
UNIQUE KEY `user_email` (`user_email`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE IF NOT EXISTS `item` (
`item_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`item_title` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`item_location` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`item_description` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`item_datetime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`item_status` int(1) unsigned NOT NULL,
PRIMARY KEY (`item_id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
http://sqlfiddle.com/#!9/fd011
I'm getting a bit confused about how to link the items to the user. It seems like I need something called a foreign key on the items, a bit like this in my item table:
FOREIGN KEY (user_id) REFERENCES user(ID)
I can't seem to get it to compile and query successfully. Can anyone please show me the right way to associate the items with the user.
You need to add the user_id column to the items table along with the constraint:
CREATE TABLE IF NOT EXISTS `users` (
`user_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`user_password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`user_email` varchar(254) COLLATE utf8_unicode_ci NOT NULL,
`user_access_level` tinyint(3) unsigned NOT NULL DEFAULT '0',
`user_active` tinyint(1) NOT NULL DEFAULT '0',
`user_activation_hash` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`user_password_reset_hash` char(40) COLLATE utf8_unicode_ci DEFAULT NULL,
`user_password_reset_timestamp` bigint(20) DEFAULT NULL,
`user_failed_logins` tinyint(1) NOT NULL DEFAULT '0',
`user_last_failed_login` int(10) DEFAULT NULL,
`user_registration_datetime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`user_registration_ip` varchar(39) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0.0.0.0',
PRIMARY KEY (`user_id`),
UNIQUE KEY `user_name` (`user_name`),
UNIQUE KEY `user_email` (`user_email`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE IF NOT EXISTS `item` (
`item_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
user_id int unsigned,
`item_title` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`item_location` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`item_description` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
`item_datetime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`item_status` int(1) unsigned NOT NULL,
PRIMARY KEY (`item_id`),
FOREIGN KEY (user_id) REFERENCES users(user_id)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The SQL Fiddle is here.
I should point out a few other things:
Pay attention to the database engine you are using. MyISAM doesn't actually enforce the relationship.
Having weird dates as the default value is probably less useful than just using NULL.
I'm not sure if there is a value to having explicit collations for every character definition, unless your database is going to be supporting a wide variety of collations.
Don't use single quotes for numeric constants. So, if a value is declared as a tinyint, set the default ot 0 not '0' (this doesn't affect performance in a CREATE TABLE statement; it is just misleading).
#GordonLindoff's solution is one method, but that assumes that each item belongs to exactly one user, and an item cannot be referenced by multiple users. If you have a many-to-many relationship, where a user can have multiple items and an item can be referenced by multiple users, then you need a third table that links them together:
CREATE TABLE IF NOT EXISTS `user_item` (
`user_id` int(11) unsigned NOT NULL,
`item_id` int(11) unsigned NOT NULL,
PRIMARY KEY (`user_item`,`item_id`),
FOREIGN KEY (user_id) REFERENCES users(user_id),
FOREIGN KEY (item_id) REFERENCES items(item_id)
)ENGINE=Innodb DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
The Foreign Key constraints enforce that for every row in user_item that the user_id exists in users, and the item_id exists in items. And as was mentioned in a previous comment, that you will need Innodb to have the foreign key constraints enforced.

Error 1215 Cannot add foreign key constraint data types match

Not sure what else to check/do. I made sure the foreign key data type matches (char(36)) and I ensured the foreign key statement uses the correct syntax
Running this script i get error 1215
USE addm;
CREATE TABLE `addm`.`notificationResource` (
`notificationId` CHAR(36) NOT NULL ,
`resourceId` CHAR(36) NOT NULL ,
PRIMARY KEY (`notificationId`, `resourceId`) ,
INDEX `fk_notificationResource_notification_idx` (`notificationId` ASC) ,
INDEX `fk_notificationResource_resource_idx` (`resourceId` ASC) ,
CONSTRAINT `fk_notificationResource_notification`
FOREIGN KEY (`notificationId` )
REFERENCES `addm`.`notification` (`id` )
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_notificationResource_resource`
FOREIGN KEY (`resourceId` )
REFERENCES `addm`.`resource` (`resourceId` )
ON DELETE NO ACTION
ON UPDATE NO ACTION);
commit;
Parent Tables:
CREATE TABLE `resource` (
`resourceId` char(36) NOT NULL,
`resourceName` varchar(255) DEFAULT NULL,
`resourceData` longblob,
PRIMARY KEY (`resourceId`),
UNIQUE KEY `resourceName_UNIQUE` (`resourceName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
CREATE TABLE `notification` (
`notificationType` varchar(5) CHARACTER SET latin1 NOT NULL,
`id` char(36) CHARACTER SET latin1 NOT NULL,
`aborted` bit(1) DEFAULT NULL,
`attempts` int(11) DEFAULT NULL,
`content` longblob,
`recordDate` datetime DEFAULT NULL,
`sent` bit(1) DEFAULT NULL,
`sentDate` datetime DEFAULT NULL,
`subject` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
`fromUser_id` bigint(20) DEFAULT NULL,
`toUser_id` bigint(20) DEFAULT NULL,
`attachmentName` varchar(100) CHARACTER SET latin1 DEFAULT NULL,
`attachmentData` longblob,
`category` varchar(255) CHARACTER SET latin1 DEFAULT NULL,
`read` tinyint(1) DEFAULT '0',
`locked` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`),
KEY `FK2D45DD0B7F734EAD` (`toUser_id`),
KEY `FK2D45DD0BE62E629E` (`fromUser_id`),
CONSTRAINT `FK2D45DD0B7F734EAD` FOREIGN KEY (`toUser_id`) REFERENCES `user` (`id`),
CONSTRAINT `FK2D45DD0BE62E629E` FOREIGN KEY (`fromUser_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8$$
I think column CHARACTER SET is different. id char(36) CHARACTER SET latin1 NOT NULL
change CHARACTER SET