0

Using MySQL I am trying to pull ALL people who's company_id matches 3 and also compare whether that person exists in the favourites table.

What I have noticed is that if a person has no job_id then they are not output by the below query.

The below query outputs 1 row, but in the people table there are 3 rows that match the company_id of 3

                SELECT *,
                           j.company_id as companyid,
                           f.id IS NOT NULL AS jid,
                           p.id as pid,
                           f.id AS fave_id,
                           f.id IS NOT NULL AS fave
                      FROM people p  
                INNER JOIN job j 
                        ON p.job_id = j.id
                 LEFT JOIN favourites f
                        ON f.people_id=p.id
                       AND f.user_id = 12
                     WHERE p.company_id = 3
                  ORDER BY p.id ASC

SQLFiddle

Any help is appreciated to get the query to output all rows that match and also check the favourites table.

1
  • you are doing an inner join on job by the job_id but don't have matching values on the person table and by matching values i mean there is a blank empty string for one row you want to see with the ON condition Commented Aug 18, 2014 at 15:53

2 Answers 2

1

If you put a left join on job, it will show people that have no job_id. I have updated the fiddle here.

SELECT
    p.*,
    j.company_id as companyid,        
    f.id IS NOT NULL AS jid,
    p.id as pid,
    f.id AS fave_id,
    f.id IS NOT NULL AS fave
FROM people p  
LEFT JOIN job j 
       ON j.id = p.job_id
LEFT JOIN favourites f 
       ON f.people_id=p.id
      AND f.user_id = 12
WHERE p.company_id = 3
ORDER BY p.id ASC
Sign up to request clarification or add additional context in comments.

1 Comment

There were some invalid dates in the data. I have updated the schema, see here: sqlfiddle.com/#!2/7fd799/10/0
1

You should change your INNER JOIN for the job table to a LEFT OUTER JOIN so they're selected regardless of whether or not they exist in the job table.

3 Comments

LEFT JOIN and LEFT OUTER JOIN are synonymous... but thats not the issue here.
The user's example used an INNER JOIN, which is what I suggested should be changed to a LEFT JOIN.
No i understand that.. if you look at the data the left join wouldn't make much a difference unless you specify NOT NULL in the select like the other answer... because there is a null value for the job_id and an empty string for the job_id in the favorites table

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.