Search code examples
sqldatabasemariadbxamppforeign-keys

SQL syntax error with foreign key when I also have primary key


#1064 - 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 'REFERENCES users(id) )' at line 8

when I try to execute my SQL statement I get the above error.

CREATE TABLE projects(
    projectId INT NOT NULL AUTO_INCREMENT,
    name VARCHAR(20) NOT NULL,
    description VARCHAR(250),
    others INT NOT NULL,
    notes TEXT,
    userId INT NOT NULL,
    CONSTRAINT fk_userId FOREIGN KEY userId REFERENCES users(id)
);

I believe the issue could have something to do with the primary key as below is a working SQL statement I wrote that also has a foreign key but no primary key

CREATE TABLE about(
    pfp longblob,
    bio VARCHAR(250) NOT NULL DEFAULT " ",
    friends INT NOT NULL DEFAULT 0,
    followers INT NOT NULL DEFAULT 0,
    id INT NOT NULL,
    CONSTRAINT fk_id FOREIGN KEY id REFERENCES users(id)
);

Solution

  • You should use parentheses. Here's a link.

    CONSTRAINT fk_userId FOREIGN KEY (userId) REFERENCES users (id)