SQL查询结果区分大小写

2025-10-23 20:04:15

1、 数据库中使用到的通配符及含义:

“.”:匹配任意单个字符。

“?”:匹配前面的子表达式0次或1次。

“+”:匹配前面的子表达式1次或多次。

“*”:匹配前面的子表达式0次或多次。x*,表示0个或多个x字符;[0-9]*,匹配任何数量的数字。

“^”:表示匹配开始位置。

“$”:表示匹配结束位置。

“[]”:表示一个集合。[hi],表示匹配h或i;[a-d],表示匹配a、b、c、d中任一个。“{}”:表示重复的次数。1{3},表示匹配3个1,即111;[0-9]{1,10},表示匹配1到10个数字。

2、 例如:

查询user库中name只以“A%B”三个字符开头的记录。

------------------------

在数据库中“%”是通配符不能直接使用。

3、 在MySQL中的方法:

1)使用转义字符\:

select * from user where name like "A\%B%";

2)$被转义:

select * from user where name like "A$%B%" escape "$";

4、 在MS SQL2005中的方法:

1)select * from user where name like "A[%]B%";

2)select * from user where name like "A$%B%" escape "$";

5、 查询结果并不是只查到了“A%B”开头的记录,例如“a%B”,小写的a或b也会被查出来。

-----------------

这是为什么呢?

原来,在数据库查询中,默认是不区分大小写的

-----------------

那如何让查询结果区分大小写呢?

6、 在MySQL中的方法:

1)select * from user where name like "A\%B%"  collate utf8_bin;

      或者

     select * from user where name  collate utf8_bin like "A\%B%" ;

collate utf8_bin放在like前后都可以。

2)select * from user where name collate utf8_bin like "A$%B%" escape "$";

-----------------------------

注:方法2中的collate utf8_bin不能放在escape "$"的后边。

utf8_bin表示建表时使用的字符集。

7、 在MS SQL2005中的方法:

1)select * from user where name collate Chinese_PRC_CS_AS like 'A$%B%' escape '$';

或者

select * from user where name like 'A$%B%' escape '$' collate Chinese_PRC_CS_AS;

collate Chinese_PRC_CS_AS放在like前后都可以。

2)select * from user where name collate Chinese_PRC_CS_AS like 'A[%]B%';

或者

select * from user where name like 'A[%]B%' collate Chinese_PRC_CS_AS;

8、Chinese_PRC_CS_AS是MS SQL2005中的排序规则。

在MS SQL2005中我们可以这样来查询排序规则:

select * from ::fn_helpcollations();

 

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢