gpt4 book ai didi

仅当值存在时Mysql字符串连接

转载 作者:行者123 更新时间:2023-11-29 09:55:51 24 4
gpt4 key购买 nike

我有一张 table

table1: ID, object1, object2, object3

只有当所有对象中都存在该值时,我才想连接object1、object2和object3

例如:

select ID, object1 +'\'+ Object2 +'\'+ object3 from table1

我希望仅当所有对象中都存在值时此查询才为 true。

当对象 2 和对象 3 中没有值时,上述查询的结果将类似于:

object1\\

但我希望输出仅作为(当对象2和对象3中没有值时)

object1 (without back slashes)

我想避免当 object2 和 object3 中没有值时出现上述查询的情况。如何编写查询以根据值的可用性动态连接?

最佳答案

使用concat_ws 。它会自动跳过空值。

mysql> select concat_ws('\\', 'foo', 'bar', null, 'baz');
+--------------------------------------------+
| concat_ws('\\', 'foo', 'bar', null, 'baz') |
+--------------------------------------------+
| foo\bar\baz |
+--------------------------------------------+

但是它不会跳过空白。

mysql> select concat_ws('\\', 'foo', 'bar', '', 'baz');
+------------------------------------------+
| concat_ws('\\', 'foo', 'bar', '', 'baz') |
+------------------------------------------+
| foo\bar\\baz |
+------------------------------------------+

好的模式不会将 null 和 '' 视为相同。但有时你别无选择。在这种情况下使用 nullif将空白变为空值。

mysql> set @var = '';
mysql> select concat_ws('\\', 'foo', 'bar', nullif(@var, ''), 'baz');
+--------------------------------------------------------+
| concat_ws('\\', 'foo', 'bar', nullif(@var, ''), 'baz') |
+--------------------------------------------------------+
| foo\bar\baz |
+--------------------------------------------------------+

你可能想把这一切变成 stored procedure .

关于仅当值存在时Mysql字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53876917/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com