---
title: "当 MySQL 和 Memcached 遇到尾部空格时"
author: "berrywu"
date: "2010-07-30T11:59:08Z"
tags: []
categories: ["编程语言"]
slug: "mysql-memcached"
draft: false
lastmod: "2010-07-30T11:59:08Z"
id: 725222
url: "https://berrywu.iteye.com/blog/725222"
---

MySQL 和 Memcached 对于同一个key，不能对应起来。最终原因是：PHP将key写入MySQL数据库之前，没有经过trim()过滤首尾空格（关键是尾部空格），结果：

　1、MySQL的varchar、char类型字段，SELECT .... WHERE 查询时忽略字段的尾部空格。例如varchar类型字段uidcode中，存储的含有尾部空格的内容“rewinx ”，通过以下三种方式均可查询到：

![](http://dl.iteye.com/upload/attachment/285615/44c528f3-34e2-356a-bb83-355f737c4dad.png)  
   
在MySQL手册第“11.4.1. CHAR和VARCHAR类型”节中写道（[http://dev.mysql.com/doc/refman/5.1/zh/column-types.html#char](http://dev.mysql.com/doc/refman/5.1/zh/column-types.html#char)）：请注意所有MySQL校对规则属于PADSPACE类。这说明在MySQL中的所有CHAR和VARCHAR值比较时不需要考虑任何尾部空格。请注意所有MySQL版本均如此，并且它不受SQL服务器模式的影响。

2、PHP 的 Memcache 扩展，则在set、get时，自动将key中的空格，转换成了半角下划线“\_”。当然，直接通过 Memcached 协议来读取，key值“rewinx ”就要写成“rewinx\_”了。  
[]()  
　　示例：testmc.php

```
<?php   
$memcache_obj = new Memcache;   
$memcache_obj->connect('192.168.8.34', 11211);   
$memcache_obj->set('rewinx ', 'hello world');   
echo $memcache_obj->get('rewinx ')."\r\n";   
?>  
```

 

![](http://dl.iteye.com/upload/attachment/285618/c28ab8a2-1810-3f54-95e4-fc8cdabe4265.png)