Skip to content
Advertisement

SQL syntax with FOREIGN KEY

I have the following tables:

CREATE TABLE
IF NOT EXISTS {}.roles_permissions
(
role_id INT
(12) NOT NULL,
permission_id INT
(12) NOT NULL,
UNIQUE KEY
(role_id,permission_id)
CONSTRAINT `fk-rprole` FOREIGN KEY
(`role_id`)
REFERENCES `roles`
(`id`)
ON
DELETE CASCADE
ON
UPDATE CASCADE
CONSTRAINT (`fs_rppermission`) FOREIGN KEY
(`permission_id`)
REFERENCES `permissions`
(`id`)
ON
DELETE CASCADE
ON
UPDATE CASCADE
)

and it thow a err:- You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ‘CONSTRAINT fs_rppermission FOREIGN KEY

what’s the problem?

Advertisement

Answer

Consider:

CREATE TABLE IF NOT EXISTS roles_permissions (
    role_id INT(12) NOT NULL,
    permission_id INT(12) NOT NULL,
    UNIQUE KEY (role_id,permission_id),
    CONSTRAINT `fk-rprole` FOREIGN KEY (`role_id`) 
        REFERENCES `roles`(`id`)
        ON DELETE CASCADE ON UPDATE CASCADE,
    CONSTRAINT `fs_rppermission` FOREIGN KEY (`permission_id`)
        REFERENCES `permissions` (`id`)
        ON DELETE CASCADE ON UPDATE CASCADE
);

Rationale:

  • there are missing commas all over your statement

  • the name of the foreign should not be surrounded with parentheses

  • … proper formatting makes the statement easier to write and read

Demo on DB Fiddle

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement