如果第1行为空,如何将数据行1更改为等于第2行?

时间:2018-02-19 01:32:28

标签: mysql sql

如果PAYMENTDATE的数据为CREATIONDATE,如何更改PAYMENTDATE的数据等于NULL的数据?例如:

+-------------+--------------+
| PAYMENTDATE | CREATIONDATE |
+-------------+--------------+
| 2018-03-21  | 2018-03-01   | 
| NULL        | 2018-04-05   |
| NULL        | 2018-07-06   |
| 2018-09-12  | 2018-08-23   |
| 2018-12-13  | 2018-11-21   |
+-------------+--------------+

这是我的疑问:

SELECT
  details.PAYMENTDATE,
  account.CREATIONDATE
FROM
  account
    INNER JOIN
  details ON account.DETAILSKEY = details.PRIMARYKEY

我尝试过使用

IF(details.PAYMENTDATE IS NULL,
    details.PAYMENTDATE = account.CREATIONDATE,
    details.PAYMENTDATE = details.PAYMENTDATE) AS NULLDATA,

但它不起作用。谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

您无需在IF语句中设置值。

IF(details.PAYMENTDATE IS NULL, account.CREATIONDATE, details.PAYMENTDATE) AS NULLDATA

您也可以使用COALESCE

COALESCE(details.PAYMENTDATE, account.CREATIONDATE) AS NULLDATA

答案 1 :(得分:1)

使用COALESCE

SELECT
    COALESECE(d.PAYMENTDATE, a.CREATIONDATE) AS PAYMENTDATE
    a.CREATIONDATE
FROM account a
INNER JOIN details d
    ON a.DETAILSKEY = d.PRIMARYKEY

COALESCE函数通过在第一个参数为NULL的情况下将第一个参数替换为第二个参数来工作,所以在

COALESCE(NULL, 3)

将返回3,但COALESCE(3, 5)将返回3.

答案 2 :(得分:1)

我认为问题出现在if中,因为你在if的第一个返回值中赋值为null

details.PAYMENTDATE = account.CREATIONDATE

您的代码应该是这样的

   SELECT
      details.PAYMENTDATE,
      IF(f.paymentdate IS NULL,
                f.CREATIONDATE,
                f.CREATIONDATE) AS NULLDATA,
      account.CREATIONDATE
    FROM
      account
        INNER JOIN
      details ON account.DETAILSKEY = details.PRIMARYKEY

只返回所需的值而不是分配其他值。

我希望我的解释很好(没有母语人士)