简体   繁体   中英

SQL Query: Complex Inner Joins and Outer Joins

Hi everyone I am currently working on an SQL sample project, trying to learn the basics of SQL and inner outer joins in general.

This is my current Database diagram:

http://imgur.com/z0Ger

I am currently stuck on 2 different queries that I am having trouble writing.

1. Given a puppy name show all the tricks it knows. 

Include:
Dog id & name
Trick id & name
Date learned & skill level

2. Given a kennel show all the puppies that have been there to learn a trick.

Include:
Kennel id & name
Date learned & trick id
Dog id & dog name

I really am stumped on these and would really appreciate it if you can help lead me to the right answer. Any help is appreciated. Thanks

First, you have a missing foriegn key between Junction_Table and Tricks but since you got the others in I assume you can fix this.

Second, the date learned and skill level belong in the junction table, not the trick table as these are functions of the combination of the dog, kennel & trick and not of the trick alone.

Having fixed that, the first query to give all dogs & tricks is:

SELECT  d.Dog_ID
       ,d.Dog_Name
       ,t.Trick_ID
       ,t.Trick_Name
       ,j.Skill_Level
       ,j.Date_Learned
FROM   Dogs d
       INNER JOIN
       Junction_Table j ON d.Dog_ID=j.Dog_ID
       INNER JOIN
       Tricks t ON t.Trick_ID=j.Trick_ID

These will give you all the tricks learned by every do that has learned at least one trick.

If you changed the INNER JOIN between Dogs and Junction_Table to LEFT JOIN you would then get all the above plus the dogs that have no tricks.

If you changed it to RIGHT JOIN you would get the dogs with 1+ trick and all the tricks including those that have no dogs.

If you changed it to FULL JOIN you would get eveything from Dogs and Tricks.

If you changed it to CROSS JOIN (and removed the ON statement) you would get a line for every dog against every trick.

The second query one I will leave you to figure out.

There is nothing tricky about joins - start with the fields you need from all tables and then work your way through the connections to tie them together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM