使用
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 |
+------------------------------------------+
好的模式不会处理空值和
''
相同的。但有时你别无选择。在这种情况下使用
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
.