I have two tables profile and name, the profile table contains some metadata relating to a user. The name table contains all the possible names the profile could have.
I am trying to create a MYSQL query that will give me the profile.age, the given name and family name for all profiles even if that dont have a given name or family name
+-------+---------+ | ID | AGE | +-------+---------+ | 0 | 10 | | 1 | 20 | | 2 | 30 | | 3 | 40 | +-------+---------+
+------------+--------+--------+ | PROFILE_ID | TYPE | NAME | +------------+--------+--------+ | 0 | 0 | Jo | | 0 | 1 | Blog | | 1 | 0 | Jim | | 2 | 1 | Smith | +------------+--------+--------+ Type 0 = Given Name Type 1 = Family Name
This is the Query I am currently using.
SELECT given.name AS 'given_name', family.name AS 'family_name', profile.age
FROM profile
LEFT OUTER JOIN name given ON profile.id = given.profile_id
LEFT OUTER JOIN name family ON profile.id = family.profile_id
WHERE given.type = 0
AND profile_id.type = 1
LIMIT 0 , 30
This is the result I want and expect to get
+------------+-------------+--------+ | GIVEN_NAME | FAMILY_NAME | ADE | +------------+-------------+--------+ | Jo | Blog | 10 | | Jim | NULL | 20 | | NULL | Smith | 30 | | NULL | NULL | 40 | +------------+-------------+--------+
However this is what I actually get
+------------+-------------+--------+ | GIVEN_NAME | FAMILY_NAME | AGE | +------------+-------------+--------+ | Jo | Blog | 10 | +------------+-------------+--------+
From what I understand LEFT OUTER JOIN should return on the NULL value joins. What am I doing wrong? How do I change my Query to return the NULL value joun?
As soon as you have a WHERE
clause on a table that is being LEFT JOIN
ed on then you will immediately eliminate the NULL
rows (i.e. where there is no match). So for starters, you should move the condition of given.type = 0
to the ON
clause instead of in the WHERE
clause. And I'm going to assume there is an issue with your other condition on the WHERE
clause.
SELECT given.name AS 'given_name', family.name AS 'family_name', profile.age
FROM profile
LEFT OUTER JOIN name given ON profile.id = given.profile_id AND given.type = 0
LEFT OUTER JOIN name family ON profile.id = family.profile_id AND family.type = 1
LIMIT 0 , 30
You are filtering type
to be 0 or 1(in where clause), this will ommit null
s.
SELECT given.name AS 'given_name', family.name AS 'family_name', profile.age
FROM profile
LEFT OUTER JOIN name given
ON profile.id = given.profile_id and given.type = 0
LEFT OUTER JOIN name family
ON profile.id = family.profile_id and profile.type = 1
LIMIT 0 , 30
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With