Skip to content
Advertisement

SELECT Primary key that refers to Foreign key

How do I write a query that compares a primary key to a foreign key to see if they refer to the same record? I was thinking something like:

SELECT BookID from books WHERE BookID = Publisher, but obviously that’s not working since they’re different numbers.

Example:

Advertisement

Answer

This line in your code means that there is another table called publisher_id in this database having a column named ID. Is that correct?

In normal scenarios, you name your table for eg: Publisher. Let ID be the primary key column of the Publisher table. It can contain more columns such as name, address etc.

Assuming one book has one publisher and one publisher can publish many books, In the books table have a column called publisher_id. Then you can reference it as a foreign key as follows (have it in the create statement just like you have done above).

If you have a publisher ID with you (for eg: 5) and want to get all the book id(s) published by this publisher, you can run the following query.

table_name.column_name is the syntax for MySQL.

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