sql基础

什么是数据库

-可存储大量数据;
-方便检索:sql语句
-保持数据的一致性、完整性;
-安全,可共享;
-通过组合分析,可产生新数据

本质:数据库其实就是拥有特殊文件结构的文件

数据库使用使用表的结构来存储数据的

表类似excle,有行有列

假设有User对象,里面name、age、sex3个属性
name | age | sex
lisi | 20 | 男

数据库的安装与使用

show databases;显示数据库列表
use 数据库名字;切换数据库
show tables;显示数据库中所有的表

sql语句

结构化查询语句,发送用户的sql语句到数据库中去进行增删改查

sql的分类

-DDL 对数据库、表的创建与修改相关进行操作的语句

创建数据库:create database name charset utf8 collate utf8_general_ci;
删除数据库:DROP DATABASE[UF EXISTS]name;

-DML 增删改语句(重点)
-DCL 对用户权限进行操作的语句
-DQL 查询语句(重点)

DML 增删改语句(重点)

insert [into]表名(字段1,字段2....) values(值1,值2....);
返回影响的行数

delete from 表名[where] 条件
返回影响的行数

update 表名 set 字段名=修改后的值1,字段名2-修改后的值2 [where]条件
返回影响的行数

sql语句DQL-基础查询(重点)

selsect 字段名 from 表名[where]条件
返回记录(表)

模糊查询 like
select * from stu where name linke "小%" ;

select * from stu where name linke "___" ;

子查询

  • 查询之中嵌套查询

  • 比较-select子查询

将查询后的结果作为参数给另一个查询语句的条件使用

select * from stu where age>(select avg(age) from stu) select * from stu where age> all(select age from stu where sex=1)

  • insert-select子查询

将选择出来的结果插入到class1表中
insert class1(cid,classname,classtype) select cid,classname,classtype from stu group by cid;

  • create-select子查询

create table class (id int(5),classname varchar(11),classtype varchar(11)) select id classname classtype from stu group by id;

高级查询

联合查询
笛卡尔积
select 字段名1,字段名2...from表1,表2 where 表1.字段=表2.字段;

内连接
select 字段名1,字段名2...from表1 inner join表2 on 表1.字段=表2.字段;

左外连接
以左边的表为主,无论左边的表字段在右边是否存在都显示
select * from 表1 left outer join 表2 on 表1.字段=表2.字段;

右外连接
以右边的表为主
select * from 表1 right outer join 表2 on 表1.字段=表2.字段;

表连接

select * from 表1 left outer join 表2 on 表1.字段=表2.字段 union
select * from 表1 right outer join 表2 on 表1.字段=表2.字段;

约束

唯一约束

主键约束:保证数据唯一

聚合函数

select count(*) from stu;

select max(age) from stu;

select min(age) from stu;

select avg(age) from stu;

分组,主要用于统计

select * from tea group by age;
having专门用于分组条件判断
where用于普通条件判断
insert class1(cid) select cid from tea group by name;

update house inner join type on house.type=type.typename set house.type=type.id;
alter table house modify type int;

删除整列

alter table worker drop deptname

你可能感兴趣的:(sql基础)