Home > Database > Mysql Tutorial > body text

How to solve the NULL problem when concatenating the CONCAT() function in MySQL

WBOY
Release: 2023-06-01 23:29:02
forward
3709 people have browsed it

The query in the project uses the concat() splicing function. In this query, the spliced ​​field is null. The splicing result is null and a null pointer exception is reported at the application layer.

SELECT CONCAT('1,',NULL,'2') result;
Copy after login

How to solve the NULL problem when concatenating the CONCAT() function in MySQL

SELECT CONCAT('1,','','2') result;
Copy after login

How to solve the NULL problem when concatenating the CONCAT() function in MySQL

It has been proved through practice that if the CONCAT() function is spliced ​​with NULL in the spliced ​​parameters, the result will be NULL.

Use the following methods to solve

Method 1: Use the IFNULL function to set it to an empty string if it is NULL.

SELECT CONCAT('1,',IFNULL(NULL,''),'2') result;
Copy after login

How to solve the NULL problem when concatenating the CONCAT() function in MySQL

Method 2: Use the CONCAT_WS function. Specify string concatenation with delimiters

SELECT CONCAT_WS(',','1',NULL,'2') result;
Copy after login

Specify using commas to separate

How to solve the NULL problem when concatenating the CONCAT() function in MySQL

##CONCAT_WS(delimiter, parameter 1, parameter 2,. ..Parameter n) and CONCAT (Parameter 1, Parameter 2, ...Parameter n)

The difference between the two functions:

CONCAT_WS() : Indicates concat with separator, that is, string connection with separator

CONCAT(): Indicates concatenation of strings

The two most important differences are, CONCAT() function, splicing If there is NULL in the parameter, NULL

will be returned directly. However, when the CONCAT_WS() function is executed, it will not return NULL

because of the NULL value.

The above is the detailed content of How to solve the NULL problem when concatenating the CONCAT() function in MySQL. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template