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

时间:2011-05-08 03:04:06

标签: mysql 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中执行此操作?

3 个答案:

答案 0 :(得分:7)

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

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小马的建议编辑静态值)

答案 1 :(得分:0)

尝试使用LEFT JOIN语句。我可能不是100%这样做,但你的一些试验和错误应该使这项工作。

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

答案 2 :(得分:0)

强制固定值第一个表上的左连接应该可以工作。

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