Solution to the problem where the CONCAT value in mysql is null

Source: Internet
Author: User

In mysql, The concat function has a feature that a value of null is returned no matter how much content the second character has. This feature makes us feel inconvenient in the instance application, but we need to use other methods to solve this problem.

In opencart development, we need to connect the user's phone number and area number in the User table, so we use the concat method,

The Code is as follows: Copy code

Select concat (isdcode, telephone) FROM gb_customer

We found many NULL columns. telephone clearly had values, so we queried the related concat method,

The description is as follows:

The Code is as follows: Copy code

Mysql CONCAT (str1, str2 ,...)

 

Returns the string generated by the connection parameter. If any parameter is NULL, the return value is NULL. There may be one or more parameters,
The isdcode value in our table may be NULL, so the value after execution is NULL. Therefore, use IFNULL to determine whether isdcode is empty.

The Code is as follows: Copy code

Select concat (IFNULL (isdcode, ''), telephone) FROM gb_customer

All values can be retrieved at this time. In addition to this method, we can specify a value by default.

Mysql built-in ifull function can be used to give a default value for the NULL Value Field During query, for example:

The Code is as follows: Copy code

Select ifnull (col1, 'default-value'), col2 from test;

When the col1 field of the test table is NULL, the database returns the default-value. Otherwise, the database returns its own value. However, when the value of the col1 field is a NULL string ("), the returned result is a NULL String because the NULL character is not NULL. If you want to replace an empty string or NULL value with default-value, ifnull is obviously not acceptable, but the case when statement can be used as an example:

The Code is as follows: Copy code

Select c1,
(Case when c2 = ''or c2 is null then 'default-value' else c2 end)
From test;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.