小编典典

SQL:如何返回不存在的行?

sql

说我有下表:

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

然后说我需要排WHERE parent_id = 50 AND language_id = 2。显然,基于示例表,我什么也得不到。但是,我仍然需要一个结果-大概是这样的:

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

有没有办法在SQL中做到这一点?


阅读 200

收藏
2021-05-23

共1个答案

小编典典

您可以对可能有效的记录和默认记录进行联合查询,然后选择第一个:

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

(根据OMG Ponies的建议,使用静态值进行编辑以进行订购)

2021-05-23