Jump to content

How to make the right join for specific results


mcmuney

Recommended Posts

I don't think you can do it in a single query with any kind of JOIN. But you can do it with a UNION using two LEFT JOINs

 

-- All Rows in Table 1 -- 
SELECT TABLE1.x, TABLE1.y, IFNULL(TABLE2.z, 0) AS z
FROM TABLE1 LEFT JOIN TABLE2 USING TABLE1.x = TABLE2.x

UNION

-- All Rows in Table 2 with no matching X in Table 1
SELECT TABLE2.x, 0, TABLE2.z
FROM TABLE2 LEFT JOIN TABLE1 ON TABLE2.x = TABLE1.x AND TABLE1.y IS NULL

ORDER BY 1

Link to comment
Share on other sites

I believe you could do this with an outer join, and a case statement. I've been working on a project in MSSQL for 2 years so I had to look up MySQL's syntax for it but I think this is correct, didn't try it.

SELECT t1.x, 
CASE t1.y
   WHEN NULL THEN 0
   ELSE t1.y
END CASE, 
CASE t2.z
   WHEN NULL THEN 0
   ELSE t2.z
END CASE
FROM t1 
OUTER JOIN t2 ON t1.x = t2.x

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.