如何使用php/mysqli将值为空的列值设置为零?

bzzcjhmw  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(353)

当连接两列(3,4)时。如果第一个值为空或null,则将其置零(0,4),如果第二个值为空或null,则将其置零,如3,0。如何在使用php的sql查询中执行。

CONCAT_WS(',',IFNULL(a.PD_right, ''),IFNULL(a.PD_left, '')) as PD_RL

在上面的代码中,连接pd\u right和pd\u left。
现在我变得
如果两个值为空,则只显示逗号(,)。
如果有两个值,它将显示为3,4
如果第一个值为空,它将显示为4
如果第二个值为空,它将显示为3,
如何解决这些问题。?我的数据库列为空。它不是null或null

ttp71kqs

ttp71kqs1#

更改此查询行:

CONCAT_WS(',',IFNULL(a.PD_right, ''),IFNULL(a.PD_left, '')) as PD_RL

CONCAT_WS(',',IFNULL(a.PD_right, 0),IFNULL(a.PD_left, 0)) as PD_RL

或者,您可以在连接之前测试这些值 CASE ...WHEN...THEN...END 语法。
更多信息请看这里。

ftf50wuq

ftf50wuq2#

如果我理解正确,只需将空字符串替换为“0”,如 CONCAT_WS(',',IFNULL(a.PD_right, '0'),IFNULL(a.PD_left, '0')) as PD_RL 应该有用。
如果要检测null或空字符串“”,请改用if函数。
我在我的机器上做了一个简单的测试,输出如下:

$ mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 9
Server version: 8.0.12 Homebrew

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

(root@localhost) [(none)]> SET @left = 3, @right = 4;
Query OK, 0 rows affected (0.00 sec)

(root@localhost) [(none)]> SELECT CONCAT_WS(',', IF(@left IS NULL OR @left = '', '0', @left), IF(@right IS NULL OR @right = '', '0', @right)) as PD_RL;
+-------+
| PD_RL |
+-------+
| 3,4   |
+-------+
1 row in set (0.00 sec)

(root@localhost) [(none)]> SET @left = 3, @right = NULL;
Query OK, 0 rows affected (0.00 sec)

(root@localhost) [(none)]> SELECT CONCAT_WS(',', IF(@left IS NULL OR @left = '', '0', @left), IF(@right IS NULL OR @right = '', '0', @right)) as PD_RL;
+-------+
| PD_RL |
+-------+
| 3,0   |
+-------+
1 row in set (0.00 sec)

(root@localhost) [(none)]> SET @left = NULL, @right = 4;
Query OK, 0 rows affected (0.00 sec)

(root@localhost) [(none)]> SELECT CONCAT_WS(',', IF(@left IS NULL OR @left = '', '0', @left), IF(@right IS NULL OR @right = '', '0', @right)) as PD_RL;
+-------+
| PD_RL |
+-------+
| 0,4   |
+-------+
1 row in set (0.00 sec)

(root@localhost) [(none)]> SET @left = NULL, @right = NULL;
Query OK, 0 rows affected (0.00 sec)

(root@localhost) [(none)]> SELECT CONCAT_WS(',', IF(@left IS NULL OR @left = '', '0', @left), IF(@right IS NULL OR @right = '', '0', @right)) as PD_RL;
+-------+
| PD_RL |
+-------+
| 0,0   |
+-------+
1 row in set (0.00 sec)

(root@localhost) [(none)]> SET @left = '', @right = '';
Query OK, 0 rows affected (0.00 sec)

(root@localhost) [(none)]> SELECT CONCAT_WS(',', IF(@left IS NULL OR @left = '', '0', @left), IF(@right IS NULL OR @right = '', '0', @right)) as PD_RL;
+-------+
| PD_RL |
+-------+
| 0,0   |
+-------+
1 row in set (0.00 sec)

相关问题