0

I am following Zed Shaw's learnSQLthehardway and I wanted to figure out how to select the names from a table person, who owned multiple pets (pets information in table pet.)

person_pet Table:    

person_id    pet_id
    0           0
    0           1
    1           1
    1           2
    2           3

person Table:

    id        name
     0         Zed
     1         Orange
     2         Limen


pet Table:

    id        name
     0         Jag
     1         Black
     2         Fluffy
     3         Mister

I have been trying to use the COUNT function but I can't seem to get the right results. I must return Zed and Orange based off this data.

SELECT name FROM person, person_pet WHERE id = 
(SELECT person_id FROM person_pet GROUP BY person_id HAVING COUNT(person_id) > 1);

This is only returning Zed and not my name. How? What could solve the problem then?

Any help would be great, thank you!

1
  • I can see many problems with this query, starting with an error "subquery returns more than one row". However, I don't see how it would only return "Zed" and nothing else. Commented Mar 20, 2015 at 21:16

1 Answer 1

1

Use SELECT from person table and IN condition from person_pet table:

SELECT name 
FROM person 
WHERE id IN 
(
    SELECT person_id from person_pet
    GROUP BY person_id
    HAVING COUNT(pet_id) > 1
)
Sign up to request clarification or add additional context in comments.

2 Comments

With the exception that it's "id" and not person_id (the first time), thank you!!! IN is what I was missing then. So COUNT basically just returns the number of times a column appears in a table, so it doesn't matter if I got person_id or pet_id
Updated query to use id instead of person_id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.