---
title: "解决MySQL查询不区分大小写"
author: "daoshud1"
date: "2012-05-30T11:31:21Z"
tags: []
categories: ["数据库"]
slug: "mysql"
draft: false
lastmod: "2012-05-30T11:31:21Z"
id: 1544718
url: "https://daoshud1.iteye.com/blog/1544718"
---

```java

今天遇到一个情况， 查询数据时查询条件输入不管大小写，都能查到同样的数据。 比如： 输入 aaa  或者aaA ,AAA都能查询同样的结果，说明查询条件是大小写不敏感的。

 

因为程序使用了hibernate框架访问mysql数据库。 一开始以为是hibernate的问题。 最跟踪了一下hibernate代码没有看到转换大小写的步骤，最后确认hibernate其实只不过是将hql转化为sql。大小写不敏感和 hibernate没有关系。

 

于是怀疑Mysql的问题。做个实验：直接使用客户端用sql查询数据库。 发现的确是大小不敏感 。

 

通过查询资料发现需要设置collate（校对） 。 collate规则：

 *_bin: 表示的是binary case sensitive collation，也就是说是区分大小写的
 *_cs: case sensitive collation，区分大小写
 *_ci: case insensitive collation，不区分大小写

 

解决方法。

1.可以将查询条件用binary()括起来。  比如：     select  * from TableA  where  columnA like binary('aaa');

2. 可以修改该字段的collation 为 binary

比如：

ALTER TABLE TABLENAME MODIFY COLUMN COLUMNNAME VARCHAR(50) BINARY CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL;

```

<http://my.oschina.net/xiangtao/blog/33983>