SQL“多字段模糊匹配关键字查询”[转载]

转载地址:
http://www.newasp.net/tech/data/24332.html

我们开发MYSQL数据库应用时,常常需要用到模糊查询。如果同一个条件需要匹配很多字段怎么办呢?通常,程序员会每个字段都在SQL中“field like'%cond%'”一次。这样,SQL语句会长得惊人,碰上复杂一点的,甚至SQL语句会因为超长而被数据库拒绝执行。其实,这个问题只要动动脑筋就很容易解决:首先,将要匹配相同条件的字段连起来(field1+field2+...)成一个长字符串;然后再 Like “%cond%”就可以了。不过这种方法有个问题,就是得权衡多表连接造成的效率降低。一般来说,单表内字段肯定应该连接后再统一like判断;表间字段,则需要先过滤后,再实行这个策略。采取这个策略,不仅可以缩短SQL,而且能够有效地提高SQL的执行效率。


例:

QUOTE:
create table orders (

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 "bei%"
 
多表的情况意思是说where子句先写连接子句进行过滤再写连接like语句进行检索
比如:
SELECT * FROM line_items l,orders o where l.order_id=o.id and concat(l.quantity,o.email) like "bei%"

其中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)
);

http://www.cnblogs.com/cmalaya/archive/2007/08/01/838309.html


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值