Skip to content
Advertisement

How to wirte an select with forigin keys and such

I am about to setup a sql db, not decided yet for mysql, mariadb or postgresql. But before that I have set up my sql script to create the tables I need.

First I need help with a sanity check, can you without me see what I am setting up here? Second, the thing I am struggeling with now is an SELECT.

I want to be able to SELECT from championship table, let me show what I want: Judge GREEN gave team YELLOW 10 points How do I get this SELECT… that is my question.

Advertisement

Answer

To achieve what you’re after you just need to join the tables together on the appropriate ID fields. This query returns the comp_score given to team YELLOW from judge GREEN:

The foreign key constraint simply stops you from deleting primary key records that are currently in use as a foreign key.

For example if you didn’t have the foreign key constraint and you deleted the record of judge GREEN from your ‘judges’ table (let’s assume the id for GREEN = 1), then you would no longer have a way to identify the judge for any record in the ‘competition’ table has a judge_id = 1.

Additionally, you can create the foreign key constraints within the create table statement:

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