SQL“多字段模糊匹配关键字查询”
时间:2008-04-24 14:16:00
我们开发数据库应用时,常常需要用到模糊查询。如果同一个条件需要匹配很多字段怎么办呢?通常,程序员会每个字段都在SQL中“field like'%cond%'”一次。这样,SQL语句会长得惊人,碰上复杂一点的,甚至SQL语句会因为超长而被数据库拒绝执行。
其实,这个问题只要动动脑筋就很容易解决:首先,将要匹配相同条件的字段连起来(field1+field2+...)成一个长字符串;然后再 Like “%cond%”就可以了。不过这种方法有个问题,就是得权衡多表连接造成的效率降低。一般来说,单表内字段肯定应该连接后再统一like判断;表间字段,则需要先过滤后,再实行这个策略。采取这个策略,不仅可以缩短SQL,而且能够有效地提高SQL的执行效率。
例:
id int not null auto_increment,
name varchar(100) not null,
email varchar(255) not null,
address text not null,
pay_type char(10) not null,
shipped_at datetime null,
primary key (id)
);
里面有数据
1 aaa aaa@gmail.com beijing cc 2006-10-11 16:17:26
现在想要查找出email为aaa开头的,address为bei开头的记录
那么一般我们会构建如下SQL
select * from orders o where o.email like "aaa%" and o.address like "bei%"
其实我们可以使用如下SQL来缩短SQL语句(也就是连接字段一起进行like操作)
SELECT * FROM orders o where concat(o.email,o.address) like "like%df%"
多表的情况意思是说where子句先写连接子句进行过滤再写连接like语句进行检索
比如:
SELECT * FROM line_items l,orders o where l.order_id=o.id and concat(l.quantity,o.email) like "3%like%"
其中line_items表
create table line_items (
id int not null auto_increment,
product_id int not null,
order_id int not null,
quantity int not null default 0,
unit_price decimal(10,2) not null,
constraint fk_items_product
foreign key (product_id) references
products(id),
constraint fk_items_order foreign
key (order_id) references
orders(id),
primary key (id)
);
标签:匹配,查询,sql
0
投稿
猜你喜欢
从事设计行业的十年
2008-04-01 09:44:00
从绘画语言的发展,看视觉设计风格
2008-08-03 17:11:00
先学会为自己做设计
2008-06-01 16:32:00
JavaScript加密解密终级指南
2008-01-03 12:25:00
Excel和Access之间的数据交换
2008-11-20 16:53:00
使用 XSLT 解释 XML 文件
2009-03-08 19:06:00
个人网站与动网整合非官方方法
2009-07-05 18:42:00
MYSQL教程:检查数据表和修复数据表
2009-03-11 15:24:00
CSS expression在IE8里正式退出历史舞台
2008-10-26 16:57:00
如何快速定位页面中复杂 CSS BUG 问题
2009-01-15 12:23:00
php基础字符串与数组知识点讲解
2023-05-25 08:28:14
如何在网页显示英语音标(附实例)
2010-01-12 17:07:00
MYSQL中怎样设列的默认值为Now()的介绍
2008-11-01 16:54:00
解析:在SQL Server下数据库链接的使用
2009-01-23 13:37:00
通过MySQL内置全文检索实现中文的相关检索
2010-06-11 13:20:00
Dreamweaver快捷键大全
2007-11-05 14:08:00
解析SQL Server中数据库快照的工作原理
2009-02-19 17:04:00
动态SQL中返回数值的实现代码
2012-01-05 18:53:54
用户研究角度看设计(1)“复制链接”的故事
2008-12-26 17:48:00
价值3亿美元的按钮[译]
2009-03-18 19:39:00