查询指定列
select 列名,列名,... from 表名; -- 例子 select id,name from student;
查询时添加常量列
SELECT pro_name商品名称 AS '商品名称',price价格 FROM product;
查询时合并
注意:合并列只能合并数值类型的字段
select sname,(servlet+jsp+html) as '总成绩' from student;
查询时去除重复记录
-- *代表所有列 select * from student; -- 去除重复列 SELECT DISTINCT sex FROM student;
条件查询(where)
逻辑条件 and or
SELECT * FROM student WHERE sex ='男' AND sname ='边通'; SELECT * FROM student WHERE sex ='女' OR sname ='张三';
比较条件 > < >= <= = <>(不等于) between and (等价于>= 且 <=)
例子
select * from student where servlet >=60; select * from student where jsp <>60; select * from student where html between 60 and 100; select * from student where html >=60 and html <=100 ;
判断条件(null和空字符串)
SELECT * FROM student WHERE sex IS NULL;-- 判断null SELECT * FROM student WHERE sex IS NOT NULL;-- 判断不是null SELECT * FROM student WHERE sname ='';-- 判断空字符串
-- 判断不是空的 SELECT *FROM student WHERE sex IS NOT NULL AND sex <>'';
模糊条件 like
SELECT * FROM product WHERE pro_name商品名称 LIKE '%索尼%';
-- % : 表示任意个字符
-- _ : 表示一个字符
聚合查询
常用的聚合函数: sum() avg() max() min() count()
-- 查询student 所有servlet总成绩,竖着 SELECT SUM(servlet) FROM student ;
-- 查询平均成绩 SELECT AVG(servlet) FROM student ;
-- 查询最大成绩 SELECT MAX(jsp) FROM student ;
-- 查询最小成绩 SELECT MIN(jsp) FROM student ; -- 查询表中多少人,*先每列统计完,选最高的列的数量 SELECT COUNT(*) FROM student ;
注意:count()函数统计的数量不包含null的数据
分页查询
limit 起始行,查询几行
起始行从0开始
SELECT * FROM student LIMIT 0,2;-- 从第一页的第0条开始,显示两条
分页查询公式
select * from student limit (当前页-1)*每页显示多少条,每页显示多少条;
查询排序
asc 顺序,升序,正序,(默认正序)
SELECT * FROM student ORDER BY html;-- 升序
-- 查询student所有的男同学html成绩顺序排序 SELECT * FROM student WHERE sex ='男' ORDER BY html;
desc 反序, 降序
SELECT * FROM student ORDER BY html desc; -- 降序
-- 升序和降序一起用 SELECT * FROM student ORDER BY jsp ASC ,html DESC; -- 先按照主排序,当字段值相同时,再次排序
分组查询 group by
-- 查询男女人数 select sex ,count(*) from student group by sex;
分组查询后筛选
注意: 分组之前条件使用where关键字,分组之后条件使用having关键字
SELECT sex ,COUNT(*) FROM student GROUP BY sex HAVING COUNT(*)>2;