0

I have two queries below that i'm sure can be combined in to one but i'm not sure how.

I want to get the first_name and email columns for every user, but I also want to get the associated pet_type and pet_breed from the first advert record if they have one. The advert record only contains a breed_id which is then linked to pet_breeds table to get the pet_type and pet_breed. I dont need to return the breed_id in the results, just the pet_type and pet_breed. If no associated advert record exists for a user then I want the pet_breed and pet_type to return the text 'None'.

SELECT users.first_name, users.email,
      (SELECT adverts.breed_id AS breed 
      FROM adverts 
      WHERE adverts.user_id = users.user_id 
      LIMIT 1)
FROM users

Second Query

SELECT pet_type, pet_breed
FROM pet_breeds
WHERE breed_id = breed

1 Answer 1

1

use LEFT JOIN and COALESCE (to show NONE instead of NULL)

SELECT  a.first_name, a.email,
        COALESCE(c.pet_type, 'NONE') pet_type,
        COALESCE(c.pet_breed, 'NONE') pet_breed
FROM    users a
        LEFT JOIN adverts b
            ON a.user_ID = b.user_ID
        LEFT JOIN pet_breeds c
            ON b.breed_ID = c.breed_ID

UPDATE 1

SELECT  a.first_name, a.email,
        COALESCE(c.pet_type, 'NONE') pet_type,
        COALESCE(c.pet_breed, 'NONE') pet_breed
FROM    users a
        LEFT JOIN 
        (
            SELECT user_ID, max(breed_ID) breed_ID
            FROM adverts
            GROUP BY user_ID
        ) b ON a.user_ID = b.user_ID
        LEFT JOIN pet_breeds c
            ON b.breed_ID = c.breed_ID
Sign up to request clarification or add additional context in comments.

2 Comments

..except it is returning multiple records where more than one adverts record exists. I only wanted it to return one record per user.
@user1052096 so you mean any of the records to be shown as long as you have to show atleast 1 pettype and petbreed?

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.