80
58

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CONCATでの文字列連結時にひとつでもNULLな項目があると「NULL」扱いになってしまう

Last updated at Posted at 2015-03-22

例えばこんな状態のテーブルがあるとします.

id column_a column_b column_c
1 a b c
2 a b NULL
3 a NULL c

で, こんなqueryを実行すると...

SELECT id, CONCAT(column_a, column_b, column_c) AS column_abc FROM `test_201503`;

こうなってしまいます.

id column_abc
1 abc
2 NULL
3 NULL

id 2の行も3の行も値が入ってるのにNULL扱いに...
これを避けるにはIFNULLを使用します.

SELECT id, CONCAT(IFNULL(column_a, ""), IFNULL(column_b, ""), IFNULL(column_c,"")) AS column_abc FROM `test_201503`;

すると, 期待していた値が表示されます.

id column_abc
1 abc
2 ab
3 ac

そもそも文字列型のカラムだとNULLでなく空文字が入ってることが多いので再現少なくて気づきにくいんですよね.

参考:
http://www.happyquality.com/2009/03/16/877.htm

80
58
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
80
58

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?