SQL“多字段模糊匹配关键字查询”
发布时间:2008-04-24 14:16:00
标签:匹配,查询,sql
我们开发数据库应用时,常常需要用到模糊查询。如果同一个条件需要匹配很多字段怎么办呢?通常,程序员会每个字段都在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)
);
0
投稿
猜你喜欢
- 前言首先明确一点这个错误只会发生在delete语句或者update语句,拿update来举例 : update A表 set A列 = (s
- 使用Windows的wmic命令,获取可执行文件的运行状况、文件路径、PID,如果可执行文件挂掉,就重启并邮件告警
- 本文实例讲述了Python3基于sax解析xml操作。分享给大家供大家参考,具体如下:python使用SAX解析xmlSAX是一种基于事件驱
- Mysql事务操作失败如何解决事务的原子性 :事务是数据库的逻辑工作单位,事务中包含的各操作要么都做,要么都不做 。要实现事务的原子性,单单
- 写在前面我的 CUDA 版本是什么? 这个问题本身就是有问题的,因为没有搞清楚cuda的分类这里的 CUDA 说的是 Driver CUDA
- 安装PIL库的时候,直接提示:Python version 2.7 required, which was not found in the
- 接口压力测试500次,查看响应时间import jsonimport requestsimport logginglogging.basic
- 最近开始学习Qt,结合之前学习过的caffe一起搭建了一个人脸识别登录系统的程序,新手可能有理解不到位的情况,还请大家多多指教。我的想法是用
- 除了使用 sys.exc_info() 方法获取更多的异常信息之外,还可以使用 traceback 模块,该模块可以用来查看异常的传播轨迹,
- *父父组件(helloWorld.vue):<template> <div class="hello-world
- Anaconda是Python的一个开源发行版本,主要面向科学计算,预装了丰富强大的库。使用Anaconda可以轻松管理多个版本的Pytho
- 下面给大家提供几个函数参考。实例一:<?php function deletedir($dir){  
- 本文实例讲述了Python实现简单生成验证码功能。分享给大家供大家参考,具体如下:验证码一般用来验证登陆、交易等行为,减少对端为机器操作的概
- 前言:Python 自带了很多的内置函数,极大地方便了我们的开发,下面就来挑几个内置函数,看看底层是怎么实现的。内置函数位于 Python/
- MySQL安装程序为您所有的MySQL软件需求提供了一个易于使用,基于向导的安装体验。产品中包含以下最新版本:MySQL服务器MySQL连接
- 简述一开始觉得这个很有趣,然后就想来做一个来玩一下使用语言: Python3使用工具:opencv视频监控 + socket数据传输技术程序
- 在vue中使用ant-design-vue组件官方地址:Ant Design Vue1. 安装首先使用vue-cli创建项目,然后进入项目,
- 字符编码,在编程中,是一个让学习者比较郁闷的东西,比如一个str,如果都是英文,好说多了。但恰恰不是如此,中文是我们不得不用的。所以,哪怕是
- <% On Error Resume Next Const uploadPath = "/uploads/"
- 交换变量 x = 6y = 5x, y = y, xprint x>>> 5print y>>>