Udders
Udders

Reputation: 6986

Mysql is it possible to do the following?

I have a mysql query, that does the following,

SELECT * FROM categoryTable 
LEFT JOIN userMenuTable 
ON userMenuTable.categoryId = categoryTable.categoryId

this returns only results that match this condition

ON userMenuTable.categoryId = categoryTable.categoryId

I was hoping it would be possible to pull all the results and also the ones from the JOIN?

Upvotes: 1

Views: 82

Answers (3)

Daniel Vassallo
Daniel Vassallo

Reputation: 344521

The result of a left outer join, as in your example, will contain all records of the "left" categoryTable, even if the join-condition does not find any matching record in the "right" userMenuTable.

On the other hand, a right outer join resembles a left outer join, except with the treatment of the tables reversed. Every row from the "right" userMenuTable will appear in the result-set at least once.

As a1ex07 suggested in another answer, it may look like you need a full outer join, which in MySQL can be emulated with a UNION between a LEFT JOIN and a RIGHT JOIN.

Upvotes: 0

I think that perhaps what you're looking for is a full outer join. MySQL does not support FULL OUTER JOIN, but you can get the equivalent using LEFT and RIGHT JOINS:

SELECT * FROM categoryTable LEFT JOIN userMenuTable
  ON categoryTable.categoryId = userMenuTable.categoryId
UNION ALL 
SELECT * FROM categoryTable RIGHT JOIN userMenuTable
  ON categoryTable.categoryId = userMenuTable.categoryId
WHERE categoryTable.categoryId IS NULL; 

Share and enjoy.

Upvotes: 0

a1ex07
a1ex07

Reputation: 37382

I think you need FULL JOIN (mysql doesn't have that syntax, but you can achieve desired result by UNION + LEFT + RIGHT JOIN)

SELECT * FROM categoryTable 
LEFT JOIN userMenuTable 
ON userMenuTable.categoryId = categoryTable.categoryId
UNION
SELECT * FROM categoryTable 
RIGHT JOIN userMenuTable 
ON userMenuTable.categoryId = categoryTable.categoryId

Upvotes: 4

Related Questions