期盼死亡的小丑 发表于 2016-11-29 10:22:54

SQLite区分大小写查询

  大部分数据库在进行字符串比较的时候,对大小写是不敏感的。
但是,在SQLite中,对大小写是敏感的。
  假设表Test的结构和值如下:
_id name 1ABCDE2abcde3ABCde4abCDE5aaaaa6bbbbb  
执行下面的SQL语句:
  select * from test where name = 'Abcde';
  结果是没有查询到任何记录。
  明显地,SQLite在进行字符串比较的时候,默认对大小写是敏感的。
  那么SQLite怎么区分大小写查询呢,以下是三种解决方案:
  
  方案一:使用大小写转换函数LOWER、UPPER
  1.select * from test where LOWER(name) = 'abcde';
  2.select * from test where LOWER(name) = LOWER('ABCDE');
  3.select * from test where LOWER(name) = LOWER('Abcde');
  4.select * from test where LOWER(name) = LOWER('ABCde');
  ....
  (1).select * from test where UPPER(name) = 'ABCDE';
  (2).select * from test where UPPER(name) = UPPER('ABCDE');
  (3).select * from test where UPPER(name) = UPPER('Abcde');
  (4).select * from test where UPPER(name) = UPPER('ABCde');
  .....
  查询到的记录都如下:
1ABCDE2abcde3ABCde4abCDE  方案二:在进行比较时强制声明不区分大小写
  select * from test where name = 'ABCDE' COLLATE NOCASE;
  查询到的记录如下:
1ABCDE2abcde3ABCde4abCDE  方案三:创建表时声明该字段不区分大小写
  create table test (_id Integer,name Text COLLATE NOCASE );
  如果在任何情况下都不需要对大小写敏感,方案三是最好的解决方案;
  如果只是少量查询对大小写不敏感,可以用方案二。
  而方案一由于用到了函数,可能有额外的性能消耗,不推荐使用。
页: [1]
查看完整版本: SQLite区分大小写查询