Monday, December 14, 2009

MySQL Including Null values in a Query

I wanted to query a database for a table that references other tables.

(a -> b) ; (a -> c)

Some of the references from a -> b are null. I wanted to include the maches for a.id = 'id' anyway.

The key is to create a table in the SELECT segment of the query.

SELECT
a.id
a.name
(SELECT b.name FROM b WHERE b.id = a.bRefId) AS NullRefCol,
a.otherCol
FROM
a
WHERE
a.status = 'active'

This query will return all 'a's that have a status that is 'active' even if the reference to 'b' is null.

No comments:

Post a Comment