遇到一个 mysql 的坑,关于字符串连接的问题,分享一下
mysql> select * from my_table;
+----+--------+------------+
| id | mod_id | mod_name |
+----+--------+------------+
| 1 | 20 | red |
| 2 | 20 | blue |
| 3 | 20 | pink |
| 4 | 21 | yellow |
| 5 | 21 | green |
| 6 | 21 | white |
| 7 | 21 | black |
| 8 | 30 | gray |
| 9 | 30 | purple |
| 10 | 30 | pinkpurple |
| 11 | 30 | red purple |
+----+--------+------------+
11 rows in set (0.00 sec)
原始表数据。
mysql> select * from my_table where mod_name in ("red", ‘blue‘, ‘pink‘, ‘purple‘);
+----+--------+----------+
| id | mod_id | mod_name |
+----+--------+----------+
| 1 | 20 | red |
| 2 | 20 | blue |
| 3 | 20 | pink |
| 9 | 30 | purple |
+----+--------+----------+
4 rows in set (0.00 sec)
使用 where 条件查询匹配列表中的列。(正常查询)
mysql> select * from my_table where mod_name in ("red", ‘blue‘, ‘pink‘ ‘purple‘);
+----+--------+------------+
| id | mod_id | mod_name |
+----+--------+------------+
| 1 | 20 | red |
| 2 | 20 | blue |
| 10 | 30 | pinkpurple |
+----+--------+------------+
3 rows in set (0.00 sec)
注意最后一组值,(‘pink‘ ‘purple‘) 中间少了个逗号,那么查询出来的结果,默认会解释为 ‘pinkpurple‘ 字符串。
mysql> select * from my_table where mod_name = (‘pink‘ ‘purple‘);
+----+--------+------------+
| id | mod_id | mod_name |
+----+--------+------------+
| 10 | 30 | pinkpurple |
+----+--------+------------+
1 row in set (0.00 sec)
使用 = 符号条件精确查询,仍然解释为 两个字符串的连接结果。
mysql> select * from my_table where mod_name = ‘pink‘ ‘purple‘;
+----+--------+------------+
| id | mod_id | mod_name |
+----+--------+------------+
| 10 | 30 | pinkpurple |
+----+--------+------------+
1 row in set (0.00 sec)
使用 = 符号条件精确查询,取消掉括弧,仍然解释为 两个字符串的连接结果。
mysql> select * from my_table where mod_name = ‘‘ ‘purple‘;
+----+--------+----------+
| id | mod_id | mod_name |
+----+--------+----------+
| 9 | 30 | purple |
+----+--------+----------+
1 row in set (0.00 sec)
头一个字符串为0长度字符串,那么合并即等于 purple 字符串。
mysql> select * from my_table where mod_name = ‘red‘‘ ‘ ‘purple‘;
Empty set (0.00 sec)
写三个字符串,其中第一个字符串的单引号和第二个字符串的单引号中间没有空格,那么解释为未知字符。。。。。
mysql> select * from my_table where mod_name = ‘red‘ ‘ ‘ ‘purple‘;
+----+--------+------------+
| id | mod_id | mod_name |
+----+--------+------------+
| 11 | 30 | red purple |
+----+--------+------------+
1 row in set (0.00 sec)
‘red‘ ‘ ‘ ‘purple‘ ,每一组字符串用空格隔开,那么就合并为 red purple 字符串。
本来,这应该报语法错误的,但是,,,,,
唉,被坑了,,,,
原文地址:http://blog.51cto.com/professor/2093120
时间: 2024-10-25 03:09:15