SQL基础增删改查

[TOC]

数据库

什么是数据库

增.png
  • 可存储大量数据;
  • 方便检索;sql语句
  • 保持数据的一致性、完整性;
  • 安全,可共享;
  • 通过组合分析,可产生新数据。
    本质:数据库其实就是拥有特殊文件结构的文件

数据库如何保存数据

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

表类似excel,有行有列

假设里面有User对象,里面有name,age,sex属性

name | age | sex

张三 | 12 | 男

李四 | 15 | 女

数据库的安装与使用

show databases; 显示数据库列表
use 数据库名字;切换数据库
show tables ;显示数据库中所有的表
desc table(表名); 查询您的表格

sql语句

结构化查询语句(增删改查) 发送用户的sql语句到数据库中取进行增删改查的操作

sql的分类

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

  • 创建数据库:create database java(数据库名字) charset utf8 collate utf8_general_ci

  • DML 增删改语句

  • 删除数据库:DROP DATABASE [IF EXISTS] mydb1;

  • DCL 对用户权限进行操作的语句

  • DQL 查询语句(重点)

入门(查询语句)

show databases; 显示数据库列表
use 数据库名字;切换数据库
show tables ;显示数据库中所有的表
desc table(表名); 查询您的表格

DML 增删改查语句(重点);

增.png

insert [into] 表名(字段1,字段,...) values();

删.png

delete form 表名 [where] 条件

update 表名 set 字段名1=修改后的值1,字段名2=修改后的值2 [where] 条件

改.png

分组

  • 分组主要就是用于统计,会配合聚合函数一起使用

  • group by

  • having 专门用于分组条件判断,注意分组的时候条件判断不能用where

select max(age) as age from stu2 group by sex having age>30;

DQL基础查询(重点)

*from 统配
select 字段名1,字段2... from 表名 [where] 条件

SQL基础增删改查_第1张图片
查.png
  • 模糊查询 like
    % 代确定的内容

select *from stu2 where name like "%%一";

一个下(_)下划线代表一个字符

select * from stu2 where name like "___";

DQL高级查询 (重点)

内连接 inner join

  • 左外连接 left outer join

以左边的表为主,无论左边的表是否存在,都出现,如果不存在,则默认为null

select *from stu2 left outer join clas on stu2.cid=cals.cid;

  • 右外连接 right outer join

  • 以右边的表为主,无论右边的表是否存在,都出现,如果不存在,则默认为null

select *from stu2 right outer join clas on stu2.cid=cals.cid;

  • 子查询

  • 子查询就是嵌套查询,即SELECT中包含SELECT,如果一条语句中存在两个,或两个以上select,那么就是子查询语句了。

SQL基础增删改查_第2张图片
下载.png
  • 比较-select子查询

select * from stu2 where age >all(select age from stu2 where sex="男");

  • #insert -select 子查询
  • 将选择出来的给结果插入到另外一个表中

insert stu1(cid) select cid from stu2 group by ;

  • 创建一个新的表,并将选择出来的给结果插入到另外一个表中

create table class1( cid int (5) not null ,calssname varchar(20),calsstype varchar(20))select cid ,calssname,calsstype from stu2 group by cid ;

聚合函数

计数

select count(*) from stu2;

最大

select max(age) from stu2;

最小

select min(age) from stu2;

平均

select avg(age) from stu2;

求和

select sun(age) from stu2;

分组, 用于统计

select count(*), age from stu2 group by age;

having 转门用于分组条件的判断
where 用于普通的条件判断

表连接

  • union ( 连接但是会去重复)

  • union all (连接所有内容)

select *from stu2 left outer join clas on stu2.cid=cals.cid

union/union all

select *from stu2 right outer join clas on stu2.cid=cals.cid;

约束(重点)

主键约束 (primary key):保证数据唯一

外键约束

唯一约束

非空约束

默认约束

事物

开启事物

start TRANSACTION;
UPDATE users set money=money-1000 where id=1;
select *from users where id =1;

UPDATE users set money=money+1000 where id=2;
select *from users where id =2;

ROLLBACK(回滚)/COMMIT(提交)

回滚 (回到开启事物之前的那个状态) 未提交数据库都可以回滚,一旦提交数据库就不能

提交,提交到数据库,无撤回操作信息

你可能感兴趣的:(SQL基础增删改查)