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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.