Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two foreign keys in postgres

I am making a junction table. I want it to have 2 separate foreign keys that reference IDs that are in 2 separate tables.

create table user_book (
    id serial primary key NOT NULL DEFAULT nextval('seq_user_prod_pk'::regclass),
    book_id numeric references books (id) NOT NULL,
    user_id numeric NOT NULL references user (id),
    checked bool,
);

I get the error:

ERROR:  syntax error at or near "user"
LINE 4:     user_id numeric NOT NULL references user (id),
                                                ^

********** Error **********

ERROR: syntax error at or near "user"
SQL state: 42601
Character: 202

Does Postgres not allow 2 foreign keys from two separate tables?

I also tried:

create table user_book (
    id serial primary key NOT NULL DEFAULT nextval('seq_user_prod_pk'::regclass),
    book_id numeric NOT NULL,
    user_id numeric NOT NULL,
    checked bool,
    foreign key (book_id) references book (id)
    foreign key (user_id) references user (id)
);

But got a very similar error.

like image 239
Rorschach Avatar asked Dec 08 '25 18:12

Rorschach


2 Answers

There's no problem with two, three or a dozen foreign keys. user is a reserved word in Postgres (and, IIRC, in ANSI SQL), so you shouldn't use it as a table name. You could, of course, escape it by using quotes ("):

create table user_book (
    id serial primary key NOT NULL DEFAULT nextval('seq_user_prod_pk'::regclass),
    book_id numeric references books (id) NOT NULL,
    user_id numeric NOT NULL references "user" (id), -- here
    checked bool,
);

But really, it's just a bad choice of name. Switch the name to a non-reserved word (e.g., users), and the problem should go away.

like image 109
Mureinik Avatar answered Dec 11 '25 10:12

Mureinik


try

create table user_book (
    id serial primary key NOT NULL DEFAULT nextval('seq_user_prod_pk'::regclass),
    book_id numeric references books (id) NOT NULL,
    user_id numeric NOT NULL references "user" (id),
    checked bool,
);

instead...

like image 22
Vao Tsun Avatar answered Dec 11 '25 10:12

Vao Tsun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!