'Mysql compound foreign key

I need to set up compound foreign key in Mysql. I think everything is set up properly but I am getting error. This is table definition dump:

CREATE TABLE `media_devices` (
  `media_id` int(11) UNSIGNED NOT NULL,
  `device_id` int(11) DEFAULT NULL,
  `location_id` int(11) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

ALTER TABLE `media_devices`
  ADD KEY `media_id` (`media_id`),
  ADD KEY `device_id` (`device_id`,`location_id`) USING BTREE;
  
CREATE TABLE `devices` (
  `id` int(11) NOT NULL,
  `device_id` int(11) DEFAULT NULL,
  `location_id` int(11) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;

ALTER TABLE `devices`
  ADD KEY `device_id` (`device_id`,`location_id`);  
  
ALTER TABLE `media_devices` ADD CONSTRAINT `media_devices_fk2` 
  FOREIGN KEY (`device_id`, `location_id`) 
  REFERENCES `lurity_global_test`.`devices`(`device_id`, `location_id`) 
  ON DELETE CASCADE ON UPDATE CASCADE;

Why it does not work. Am I missing something? Obviously yes.

Thanks please.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source