MySQL常用指令--数据过滤、用通配符进行过滤
一、数据过滤
1.1 组合where子句
MySQL允许给出多个where子句。通常以and或or的子句方式进行使用。操作符用来联结或改变where子句中的关键字,也称为逻辑操作符。
1.1.1 and操作符
//where应在from后;从表中挑选出LocationX = 1198 并且LocationY <=770的设备序号、设备名称及X坐标信息
select DeviceNO,DeviceName,LocationX from device where LocationX = 1198 and LocationY <=770;
1.1.2 or操作符
//从表中挑选出LocationX = 1198 或者LocationY =770的设备序号、设备名称及X\Y坐标信息
select DeviceNO,DeviceName,LocationX,LocationY from device where LocationX = 1198 or LocationY =770;
1.1.3 计算次序
where可包含任意数目的and和or操作符。允许两者结合以进行高级复杂的过滤。
//从表中搜索DeviceNO=001或DeviceNO=010,并且LocationX小于或等于550;
//DeviceNO,DeviceName,LocationX,LocationY信息
//(and优先级高于or!!!DeviceNO=001 or DeviceNO=010 and LocationX<=550可能会有歧义!!!)
//防止歧义,需要添加()
select DeviceNO,DeviceName,LocationX,LocationY from device where (DeviceNO=001 or DeviceNO=010) and LocationX<=550;
1.2 IN操作符
圆括号在where字句中还有另外一种用法,in操作符用来指定条件范围,只要是范围中的每个条件都可以进行匹配。
in取合法值的由逗号分割的清单,全都扩在圆括号中。
//case1;
//在DeviceNO=001和DeviceNO=003中的所有数据(DeviceNO,DeviceName,LocationX,LocationY)
select DeviceNO,DeviceName,LocationX,LocationY from device where DeviceNO IN (001,003) ORDER BY LocationX;
//case2;或者使用or语句
select DeviceNO,DeviceName,LocationX,LocationY from device where DeviceNO=001 or DeviceNO=003 order by LocationX;
//case1,case2结果是一样的;
1.3 NOT操作符
//除了DeviceNO=001和DeviceNO=003外的所有数据(DeviceNO,DeviceName,LocationX,LocationY)
select DeviceNO,DeviceName,LocationX,LocationY from device where DeviceNO NOT IN (001,003) ORDER BY LocationX;
二、用通配符进行过滤
2.1 like操作符
为在搜索字句中使用通配符,必须使用like通配符。like指示MySQL,后跟的搜索模式利用通配符匹配而不是直接相等匹配进行比较。
2.1.1 百分号(%)通配符
%表示任何字符出现的任意次数。
//从表中搜索DeviceName设备名称以烟支空头检测开头的词
select DeviceNO,DeviceName,LocationX,LocationY from device where DeviceName like '烟支空头检测%';
//区分大小写,根据MySQL配置方式,搜索可以是区分大写的,若区分大写,'jet%'与'JetPack%'将不匹配!!!
//也可以使用多个通配符
select DeviceNO,DeviceName,LocationX,LocationY from device where DeviceName like '%烟支空头检测%';
区别如下图所示:使用一个通配符,搜索到一个结果;使用两个通配符,搜索到两个结果。
//通配符还可以出现在搜索模式的中间位置;如:搜索以'烟'开头,以'测'结尾的所有产品;
select DeviceNO,DeviceName,LocationX,LocationY from device where DeviceName like '烟%测';
2.1.2 下划线(_)通配符
下划线与%用途一样,但下划线仅匹配单个字符而不是多个字符
select DeviceNO,DeviceName,LocationX,LocationY from device where DeviceName like '_烟支空头检测%';
//通配符放在后面,仅有一个检测结果
select DeviceNO,DeviceName,LocationX,LocationY from device where DeviceName like '烟支空头检测%';
//通配符放在前面,有2个检测结果
select DeviceNO,DeviceName,LocationX,LocationY from device where DeviceName like '%烟支空头检测';
2.2 使用通配符技巧
2.2.1 不要过度使用通配符。
2.2.2 仔细注意通配符位置。
2.2.3 在确实需要使用时。