多条件查询的MYSQL语句实现(MYSQL语句的拼装)
2016-09-25 23:55
1731 查看
多条件查询的实现
本文主要介绍在筛选商品等信息时,实现多条件筛选的功能。(本文使用php编写)
举例如下:如同时实现三个条件的查询:
1.排序(按价格,销量等排序)
2.产品尺寸(3寸以下,3-5寸,5寸以上)3.按品牌筛选
首先创建数据库表:
1.产品表
<pre name="code" class="sql"> create table product ( id int(11), name varchar(20), sales_num int(11), size int(5), is_sales int(5), brand_id int(11), primary key(id) );
2.产品价格表
<pre name="code" class="sql"> create table product_brand ( id int(11), product_id int(11), brand_name float, primary key(id) );
create table product_brand ( id int(11), product_id int(11), brand_name float, primary key(id) );
实现方法如下:
</pre><pre name="code" class="php"> <?php class Product{ public function showProductList($sort_type_id=null,$size_id=null,$brand_id=null){ $servername='localhost'; $username='username'; $password='password'; $dbname='myDB'; switch ($sort_type_id) { //按价格排序 case 1: $sort_type_info=' order by product_price.price ASC'; break; //按销量排序 case 2: # code... $sort_type_info=' order by product.sales_num DESC' break; default: # code... $sort_type_info=''; break; } switch ($size_id) { //尺寸小于3 case 1: $size_info=' and product.size < 3'; break; //尺寸3-5 case 2: $size_info=' and product.size in (3,5)'; break; //尺寸大于5 case 3: $size_info=' and product.size > 5'; break; default: $size_info=''; break; } switch ($brand_id) { //未输入品牌 case null: $brand_info=''; break; //根据品牌id筛选 default: $brand_info=' and product.brand_id='.$brand_id; break; } $conn=new mysqli($servername,$username,$password,$dbname); if ($conn->connect_error) { die('connect failed'); } 拼装sql语句 $sql='select product.id as product_id,product.name as product_name,product_price.price,product_brand.name as product_brand_name from product inner join product_price on product.id=product_price.product_id inner join product_brand on product.id=product_brand.product_id where product.is_sales=1'.$size_info.$brand_info.$sort_type_info; $result=$conn->query($sql); $conn->close(); return $result; } } ?>
相关文章推荐
- MySQL中使用case when 语句实现多条件查询的方法
- mysql 下 计算 两点 经纬度 之间的距离 含具体sql语句以及伪列作为查询条件实现
- mysql group by内排序的实现以及having和where 条件语句查询的区别
- MySQL中使用case when 语句实现多条件查询的方法
- MySQL中根据if标签实现多条件模糊查询(动态SQL语句)
- MySQL中使用case when 语句实现多条件查询的方法
- Mysql实现文章查询上一篇和下一篇功能,附sql语句?
- 【MySQL】如何使用C#+MySQL实现一条MySQL语句进行多表查询
- Mysql语句实现多表查询问题[试题]
- 单个select语句实现MySQL查询统计次数
- MySql的sql语句中添加存储过程或者存储函数来实现Oracle中的start with ……connect by prior……递归(树形结构数据)查询
- MySQL IFNULL中可以有select语句;查询一个表中的数据,同时查看另一个表中是否有符合条件的额数据
- MySQL一条语句实现同时查询和修改
- asp下实现多条件模糊查询SQL语句
- mysql中sql实现查询当天、昨天、本月、季度的语句
- C#/Java 程序执行MySqL 中文条件查询语句查询异常
- sql查询语句查询条件字段的拼装
- 单个select语句实现MySQL查询统计次数
- MySQL中动态生成多条件查询语句
- sql 自定义函数 ,where后拼接条件跳转语句,实现可变参数查询