MySql的字符串“=”查询优化

字符串查询是比较耗时的,尤其是字符串比较长,且数据量多的时候。这里要介绍MySql的一个函数CRC32(expr),该函数是把字符串重新编码,生成一个唯一bigInteger的数字,通过比对两个数字来间接查询字符串。由于它生成是按照整个字符串去生成的,因此只能用“=”去查询,不能用like/>/<这个范围查询。Java的API也有CRC32类库,主要用于校验数据的准确性。看示例代码:

MySql的CRC32(expr)的查询示例:

SQL:select CRC32('A'), CRC32('B'), CRC32('C'), CRC32('D'), CRC32('AB'), CRC32('AD');
返回结果:
<table border="1" cellpadding="1" cellspacing="1" width="200"><tbody><tr><td><pre name="code" class="sql">CRC32('A')
CRC32('B')
CRC32('C')
CRC32('D')
CRC32('AB')
CRC32('AD')
35542544751255198513103756586327464442928122071113641370930
 

 

Java API的CRC32使用实例:

@Test
public void test() {
	CRC32 crc = new CRC32();
	String strA = "A";
	String strB = "B";
	String strC = "C";
	String strD = "D";
	String strAB = "AB";
	String strAD = "AD";
		
	crc.update(strA.getBytes()); 
	System.out.println(crc.getValue()); // 3554254475
	
	crc.update(strB.getBytes()); 
	System.out.println(crc.getValue()); // 812207111
		
	crc.reset(); // 重置CRC元素,若不重置,则生成的CRC的值是strA+strB,结果是"AB"进行编码
	crc.update(strB.getBytes());
	System.out.println(crc.getValue()); // 1255198513
		
	crc.reset();
	crc.update(strC.getBytes());
	System.out.println(crc.getValue()); // 1037565863
		
	crc.reset();
	crc.update(strD.getBytes());
	System.out.println(crc.getValue()); // 2746444292
		
	crc.reset();
	crc.update(strAB.getBytes());
	System.out.println(crc.getValue()); // 812207111
		
	crc.reset();
	crc.update(strAD.getBytes());
	System.out.println(crc.getValue()); // 3641370930
	}
从上述来看,相同的字符串使用MySQL和Java的CRC32编码后的值是相同的。但是值的大小跟字符的大小无关。

在Mysql,若把CRC32生成的数值存储到数据库,那这就是冗余的数值,以冗余来换查询效率,有时候是值得的。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值