外贸网站建设电话,南昌高端网站制作,国内免费的ftp服务器,石景山区网站建设一.概念 数据查询不应只是简单返回数据库中存储的数据#xff0c;还应该根据需要对数据进行筛选以及确定数据以什么样的格式显示。
二.语法格式 select 列名 from 表 where 条件 1.查询所有的商品
select * from product;
2.查询商品名和商品价格
select pname,price from…一.概念 数据查询不应只是简单返回数据库中存储的数据还应该根据需要对数据进行筛选以及确定数据以什么样的格式显示。
二.语法格式 select 列名 from 表 where 条件 1.查询所有的商品
select * from product;
2.查询商品名和商品价格
select pname,price from product; 3.别名查询
使用关键字asas可以省略
表别名
select * from product as p;
select * from product p;
列别名
select pname as 商品名,price as 商品价格 from product;
4.去掉重复值
select distinct price from product;
5.运算查询
select pname,price10 from product;
三.运算符
1.算数运算符 - * / %
2.比较运算符 1 安全的等于两个操作数均为null时其所得值为1当一个操作数为null时其所得值为0. 2 或! 不等于 3IS NULL或ISNULL 判断一个值是否为NULL 4IS NOT NULL 5LEAST 返回最小值 6GREATEST 返回最大值 7BETWEEN AND 判断一个值是否落在两个值之间 8IN 判断一个值是列表中的任意一个值 9NOT IN 10LIKE 通配符匹配 11REGEXP 正则表达式匹配 注
1通配符是一种特殊语句主要有星号*和问号用来模糊搜索文件。当查找文件夹时可以使用它来代替一个或多个真正字符当不知道真正字符或者懒得输入完整名字时常常使用通配符代替一个或多个真正的字符。
2正则表达式又称规则表达式,Regular Expression在代码中常简写为regex、regexp或RE是一种文本模式包括普通字符例如a 到 z 之间的字母和特殊字符称为元字符是计算机科学的一个概念。正则表达式使用单个字符串来描述、匹配一系列匹配某个句法规则的字符串通常被用来检索、替换那些符合某个模式规则的文本。
3.逻辑运算符 1NOT或 逻辑非 2AND或 逻辑与 3OR或|| 逻辑或 4XOR 逻辑异或 四.运算符的应用
1.算数运算符
select pname,price10 as new_price from product;
2.比较运算符/逻辑运算符
select * from product where pname海尔洗衣机;
select * from product where price800;
select * from product where price in (200,800);
select * from product where pname like %裤%;
%用来匹配任意字符
select * from product where pname like _%蔻;
_下划线匹配单个字符
select * from product where category_id is null;
不能够使用因为null不等于任何值。
求最小值和最大值时如果有一个值为null则不进行比较结果直接为null。 五.排序查询
对读取的数据进行排序使用order by语句 语法格式 select 字段名1字段名2…… from 表名 order by 字段名1 [asc,desc]字段名2 [asc,desc] asc表示升序desc表示降序默认升序
order by 子句放在查询语句的最后面。limit子句除外 select * from product order by price desc;
select * from product order by price desc , category_id desc;
select distinct price from product order by price desc;
六.聚合查询
之前我们做的查询都是横向查询而聚合查询是对一列的值进行计算返回一个值。
1.查询商品的总条数
select count(pid) from product;
select count(*) from product;
查询所有记录不为空的条数
select count(pid) from product where price200; 2.查询总和
select sum(price) from product where category_idc001;
3.查询最大/最小价格
select max(price) from product;
select min(price) from product;
4.查询平均价格
select avg(price) from product where category_idc002;
5.聚合查询对于null的处理
1.count函数对null值的处理
如果count函数的参数为*则统计所有记录的个数。如果参数为某字段则不统计含null值的记录个数。
2.sum/avg/max/min对null值的处理
忽略null值的存在 七.分组查询group by
对查询信息进行分组
select category_id,count(id) from product group by category_id;
分组之后select后面只能写分组字段和聚合函数。 分组之后的条件筛选——having
分组之后对统计结果进行筛选不能够使用where
having子句用来从分组的结果中筛选行。
select category_id,count(id) cnt from product group by category_id having cnt4;
SQL的执行顺序
from -group by -count -select -having -order by 八.分页查询limit
采用分页显示方式。
limit mn
m整数表示从第几条索引开始
n整数表示查询多少条数据 select * from product limit 5;
显示前5条
select * from product limit 3,5;
从第四条开始显示显示5条。 九.数据导入
将一张表的数据导入到另一张表中
格式 insert into table2 select * from table1
要求目标表2必须存在。
insert into product3 select category_id , count(*) from product group by category_id;
十.总结