JAVAEE

JAVAEE——基本SQL查询总结

2018-03-08  本文已影响16人  So_ProbuING

SQL语句分为三类

  1. 数据定义语言:简称DDL(Data Definition Language)用来定义数据库对象:数据库DataBase,表table,列column等。关键字:创建create 修改alter 删除drop等
  2. 数据库操作语言:简称DML(Data Manipulation Language) 用来对数据库中表的记录进行更新。关键字:插入 insert,删除delete 更新 update等
  3. 数据查询语言:简称DQL(Data Query Language)用来对数据库中表的记录进行查询。关键字:select,from,where等
  4. 数据控制语言:简称DCL(Data Control Language) 用来定义数据库的访问权限和安全级别及创建用户,关键字 grant等

SQL查询回顾

回顾查询我们使用一个案例:创建一个product商品表

建表语句

create table product (
  pid INT PRIMARY KEY auto_increment,
  pname varchar(20),
  price double,
  pdate timestamp
);

查询语法

select [distinct]* | 列名,列名 from 表(where 条件)

简单查询

select * from product
select pname,price from product;
select * from product as p;
# 使用别名
select * from product p ;
select pname as name from product;
select pname name from product;
select distinct(price) from product;
select pname,price+10 from product;

条件查询

select * from product where pname like ‘%新%’;
select * from product where pid in (2,5,8);
select * from product where pid =1 or pid =2 or pid =3;
select * from product where pname = '左慈';
select * from product where price>60;
select * from product where pname like '%士%'
select * from product where pid in (3,6,9);
select * from product where pname like '%士%' and pid >4;
select * from product where pid =2 or pid =6;

排序

语法

select * from 表名 order by 字段1 asc|desc 字段2 asc|desc (asc 升序 desc 降序)
order by 必须放到语句的最后面

select * from product order by price asc;
select * from product order by price desc;
select * from product where pname like '%士%' order by price desc;

聚合

*常用的聚合函数:
* sum() 求和
* avg() 平均
* max() 最大值
* min() 最小值
* count() 计数
聚合函数不统计Null值

select sum(price) from product;
select avg(price) from product;
select count(*) from product

分组操作 group by

分组后的条件不能再使用where 而要使用having

alter table product add civ varchar(32);
update product set cid = '1'
update product set cid='2' where pid in (5,6,7)
select cid,count(*) from product  group by cid;
select avg(price) from product group by cid having avg(price)>20000

limit分页

select * from product limit 6,3 每页显示3条记录要查询第三页
上一篇 下一篇

猜你喜欢

热点阅读