Lorenzo
Lorenzo

Reputation: 9

How to combine 3 tables in SQL

im using SQL and i have three tables: Owner, PetType and PetAndOwner. i want to list all the people in the owner table who own a dog. these are the tables and their attributes

https://i.sstatic.net/hkXu7.jpg

the trouble that im having is that i cant seem to find the right code to use to be able to find out which owners have dogs because you have to get the data from the PetAndOwner table and then join it back with the other tables to print the data.

my final result should show all owners names who have a dog

Upvotes: 0

Views: 63

Answers (1)

DM9123
DM9123

Reputation: 9

There seems to be a missing table in your query, so assuming that table holds details of a pet:

SELECT Owner.FirstName,Owner.LastName,Pet.Name 
 FROM PetType 
    JOIN Pet ON Pet.PetTypeId = 1 AND PetType.PetTypeId = Pet.PetTypeId
    JOIN PetAndOwner ON Pet.PetId = PetAndOwner.PetId 
    JOIN Owner ON  Owner.ownerId = PetAndOwner.ownerId 

Here is a Demo

Upvotes: 1

Related Questions