Skip to content
Advertisement

Nasty sql error(POSTGRES) “There is no unique constraint matching given keys for referenced table…”

EDIT: tables have been translated from my language to english i’ve changed te reference of foreign key in table Comment to “Utente” -> “User”

Hi everyone i’m trying to build a small review system in sql as follows. Every user can comment on some item(could be anything) and any other user can answer any comment. The Admin of the website cannot post comments itself, he/she can only answers to user’s comments… Here’s the code explained step by step.

Tables to define entities “User” and “Comment”

Every User can post Comments on specific items and any user can also answers Comments like this:

The admin of the website cannot post comments itself, he/she can only answers to other’s comments so i’ve created these tables

Postgres says “There is no unique constraint matching keys for referenced table ‘Comment'”… I’ve look at some answers and i’ve tried to add ‘unique’ to the attributes of my table ‘User’, but i can’t get over it. The ddl file in pretty large so if needed i’ll post more code. Thanks for answering!

Ps. i know it would be easier to have some attributes like “CommentId” or “UserId” but, unfortunately the project requires to be implented this way.

Advertisement

Answer

Typos excluding adding a unique constraint to your comment table before the Answer table is created will prevent this error. You can do this as a standalone statement such as below:

Or you can update the table script to include it at time of the table creation:

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