Skip to content

Instantly share code, notes, and snippets.

@ken-muturi
Created July 3, 2014 11:39
Show Gist options
  • Select an option

  • Save ken-muturi/8da2bd99973458eb8df6 to your computer and use it in GitHub Desktop.

Select an option

Save ken-muturi/8da2bd99973458eb8df6 to your computer and use it in GitHub Desktop.
Left Join Null Column
What Comes
-------------------------------------------------
id | type | pet_name
1 | aardvark | NULL
2 | dog | Charlie
3 | dog | Rover
4 | cat | Tabby
5 | cat | Sandy
6 | cat | MeowMeow
Required
-------------------------------------------------
id | type | petname
1 | aardvark | NULL
2 | dog | Charlie
3 | NULL | Rover
4 | cat | Tabby
5 | NULL | MeowMeow
6 | NULL | Sandy
SELECT id,
IF(type=@prev,NULL,@prev:=type) AS type,
petname
FROM (
select pt.*, pn.pet_name
from PET_TYPES pt
left join PET_NAMES pn on pt.id=pn.type_id
) AS list,
(SELECT @prev:='') AS init
ORDER BY list.type, list.id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment