开发者

SQL: How to return an non-existing row?

开发者 https://www.devze.com 2023-03-03 12:33 出处:网络
Say I have the following table: ================================================= color_id | parent_id | language_id | name|

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   开发者_StackOverflow     | 2           | NULL     |
-------------------------------------------------

Is there a way to do this in SQL?


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)


try working with LEFT JOIN statement. i'm probably not doing this 100% but a bit of trial and error on your part should make this work.

SELECT table1.field1, table1.field2, table2.field3, table2.field4
FROM my_table table1 
LEFT JOIN my_table table2 ON table1.field1=table2.field1 OR table1.field2=table2.field2


a left join on a forced fixed value first table SHOULD work.

select 
      YourTable.color_id,
      ForcedSQL1Record.parent_id,
      ForcedSQL1Record.language_id,
      YourTable.name
   from 
      ( select 50 as Parent_ID,
                2 as Language_ID
            from YourTable
            limit 1 ) ForcedSQL1Record
      left join
         YourTable
            on ForcedSQL1Record.Parent_ID = YourTable.Parent_ID
            AND ForcedSQL1Record Language_ID = YourTable.Language_ID
0

精彩评论

暂无评论...
验证码 换一张
取 消