【问题标题】:returning 0 as value for non-existing row返回 0 作为不存在行的值
【发布时间】:2013-05-29 09:47:56
【问题描述】:

我有两张桌子。

表 1:

-------------------------------
| product_id | product number |
-------------------------------
|    1001    |   67E432D      |
|    1002    |   888CDE32     | 
|    1003    |   54D32EC2     |
-------------------------------

表 2:

--------------------------
| product_id |   desc    |
--------------------------
|  1001      | product 1 |
|  1003      | peoduct 3 |
--------------------------

加入表 1 和表 2 后,我得到以下结果。

-------------------------------------------
| product_id | product number |   desc    |
-------------------------------------------
|    1001    |   67E432D      | product 1 |
|    1002    |   888CDE32     |           |
|    1003    |   54D32EC2     | product 3 |
-------------------------------------------

现在您可以看到产品 3 的“desc”列现在是空的。我怎么可能在该列中有一个 0?比如:

-------------------------------------------
| product_id | product number |   desc    |
-------------------------------------------
|    1001    |   67E432D      | product 1 |
|    1002    |   888CDE32     |     0     |
|    1003    |   54D32EC2     | product 3 |
-------------------------------------------

可能有一些功能可以完成这项工作,但我想我还不知道。

【问题讨论】:

  • 考虑将列名 desc 更改为 description - desc 是 SQL 关键字。

标签: sql oracle plsql oracle11g plsqldeveloper


【解决方案1】:

听起来你只想使用NVL

SELECT product_id, product_number, NVL( desc, '0' )
  FROM table_1
       LEFT OUTER JOIN table_2 USING (product_id)
ORDER BY product_id

SQLFiddle Demo

【讨论】:

    【解决方案2】:

    由于这个问题被标记为 Oracle,贾斯汀的回答很好。

    如果您关心可移植性,请考虑使用 coalesce:根据 Justin 的回答:

    SELECT product_id, product_number, coalesce( desc, '0' )
      FROM table_1
           LEFT OUTER JOIN table_2 USING (product_id)
    ORDER BY product_id
    

    至于区别看here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-19
      • 2021-01-14
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 2023-03-09
      相关资源
      最近更新 更多