带有NULL行的MySql乘法列

时间:2016-08-27 16:27:37

标签: mysql sql select null

我有这个SQL表:

+----+-------------+----------+------+-------+
| ID | DESCRIPTION | QUANTITY | EACH | PRICE |
+----+-------------+----------+------+-------+
| 1  | Product 1   |     1    |  12  | 1*12  |
| 2  | Product 2   |     2    |   3  | 2* 3  |
| 3  | Prodcut 3   |   NULL   |   3  |       |
+----+-------------+----------+------+-------+

这个查询:

SELECT
  DESCRIPTION,
  QUANTITY,
  EACH,
  (QUANTITY*EACH) AS PRICE
FROM table1

我想用 1 替换 NULL ,我想在PRICE列中进行乘法运算。 我不想使用 UPDATE ,因为我无法更改table1中的值。

3 个答案:

答案 0 :(得分:1)

COALESCE返回其参数的第一个非空值

SELECT DESCRIPTION,
       QUANTITY,
       EACH,
       coalesce(QUANTITY, 1) * EACH AS PRICE
FROM table1

答案 1 :(得分:1)

您可以使用coalesce表达式来获取值而不是null

SELECT
  DESCRIPTION,
  QUANTITY,
  EACH,
  COALESCE(QUANTITY, 1) * EACH AS PRICE
FROM table1

答案 2 :(得分:0)

你也可以使用IFNULL:

SELECT id, description, quantity, each,
IFNULL(quantity,1)*each AS price
FROM Table