MySQL函数concat多个字段模糊查询不匹配问题
表结构
1 | CREATE TABLE `user_address` ( |
表数据
1 | INSERT INTO `publisher`.`user_address`(`id`, `name`, `phone`, `zip_code`, `address_district`, `address_road`, `address_detail`, `user_id`, `create_time`, `update_time`, `status`) VALUES (8, '王林', '13061111111', '261234', 6, '永清路', '173号', 12, NULL, '2022-03-09 17:23:35', 1); |
查询语句
1 | mysql> SELECT * FROM user_address WHERE CONCAT(address_road, address_detail) LIKE '%永清路%'\G |
具体原因
MySQL :: Reference Manual :: 12.8 String Functions and Operators
CONCAT()
returns NULL if any argument is NULL.
1 | mysql> SELECT CONCAT('My', NULL, 'QL')\G |
解决方案一:
将 address_detail 字段的默认值由 NULL
改为 Empty String
。
解决方案二:
使用
IFNULL
优化查询语句1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26mysql> SELECT * FROM user_address WHERE CONCAT(address_road, IFNULL(address_detail, "")) LIKE '%永清路%'\G
*************************** 1. row ***************************
id: 8
name: 王林
phone: 13061111111
zip_code: 261234
address_district: 6
address_road: 永清路
address_detail: 173号
user_id: 12
create_time: NULL
update_time: 2022-03-09 17:23:35
status: 1
*************************** 2. row ***************************
id: 16
name: 徐三
phone: 13071111111
zip_code: NULL
address_district: 3
address_road: 永清路
address_detail: NULL
user_id: 6
create_time: NULL
update_time: 2022-03-11 10:28:20
status: 1
2 rows in set (0.01 sec)
将
concat
改为concat_sw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26mysql> SELECT * FROM user_address WHERE CONCAT_WS('', address_road, address_detail) LIKE '%永清路%'\G
*************************** 1. row ***************************
id: 8
name: 王林
phone: 13061111111
zip_code: 261234
address_district: 6
address_road: 永清路
address_detail: 173号
user_id: 12
create_time: NULL
update_time: 2022-03-09 17:23:35
status: 1
*************************** 2. row ***************************
id: 16
name: 徐三
phone: 13071111111
zip_code: NULL
address_district: 3
address_road: 永清路
address_detail: NULL
user_id: 6
create_time: NULL
update_time: 2022-03-11 10:28:20
status: 1
2 rows in set (0.00 sec)
1 | mysql> SELECT USER.* |