Advertisement
Guest User

Untitled

a guest
Apr 20th, 2014
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. A.id A.name B.id B.name C.id C.name
  2. -----------------------------------
  3. 1 Thing 2 Bee NULL NULL
  4. 1 Thing NULL NULL 1 Cow
  5.  
  6. (
  7. SELECT
  8. A.id AS a_id,
  9. A.name AS a_name,
  10. B.id AS b_id,
  11. B.name AS b_name,
  12. /* Substitute NULLs... for the other table C, for *all columns* */
  13. NULL AS c_id,
  14. NULL AS c_name,
  15. NULL AS other_c
  16. /* etc, other cols from C */
  17. FROM A
  18. LEFT JOIN B ON A.id = B.a_id
  19. /* UNION, rather than UNION ALL in case both tables have NULLs */
  20. ) UNION (
  21. SELECT
  22. A.id AS a_id,
  23. A.name AS a_name,
  24. /* This time substitute NULLs for B, again *all columns* */
  25. NULL AS b_id,
  26. NULL AS b_name,
  27. C.id AS c_id,
  28. C.name AS c_name
  29. C.other_c
  30. FROM A
  31. LEFT JOIN C ON A.id = C.a_id
  32. )
  33. ORDER BY
  34. a_id,
  35. /* sort the non-null B ahead... */
  36. CASE WHEN b_id IS NOT NULL THEN 0 ELSE 1 END
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement