Into
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
Tables
Profile
+-------+---------+
| ID | AGE |
+-------+---------+
| 0 | 10 |
| 1 | 20 |
| 2 | 30 |
| 3 | 40 |
+-------+---------+
Name
+------------+--------+--------+
| PROFILE_ID | TYPE | NAME |
+------------+--------+--------+
| 0 | 0 | Jo |
| 0 | 1 | Blog |
| 1 | 0 | Jim |
| 2 | 1 | Smith |
+------------+--------+--------+
Type 0 = Given Name
Type 1 = Family Name
Quert
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
Problem
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
WHEREclause on a table that is beingLEFT JOINed on then you will immediately eliminate theNULLrows (i.e. where there is no match). So for starters, you should move the condition ofgiven.type = 0to theONclause instead of in theWHEREclause. And I’m going to assume there is an issue with your other condition on theWHEREclause.