Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: How to return an non-existing row?

Tags:

sql

mysql

Say I have the following table:

=================================================
| color_id | parent_id | language_id | name     |
=================================================
| 1        | 50        | 1           | Black    |
-------------------------------------------------

Then say I need the row WHERE parent_id = 50 AND language_id = 2. Obviously, I would get nothing back based on my example table. However, I still need a result -- probably something like this:

=================================================
| color_id | parent_id | language_id | name     |
=================================================
| NULL     | 50        | 2           | NULL     |
-------------------------------------------------

Is there a way to do this in SQL?

like image 924
StackOverflowNewbie Avatar asked May 08 '11 03:05

StackOverflowNewbie


1 Answers

You could do a union query of both the potentially valid record and your default, then select the first one:

SELECT * FROM
(SELECT color_id, parent_id, language_id, name, 1 as order_rank
 FROM some_table
 WHERE parent_id = %parent_id% AND language_id = %language_id%
 UNION
 SELECT NULL, %parent_id%, %language_id%, NULL, 2 as order_rank
)
ORDER BY order_rank
LIMIT 1

(Edited with static value for ordering as suggested by OMG Ponies)

like image 50
MPelletier Avatar answered Sep 22 '22 20:09

MPelletier