SQL数据库基本操作

基本SQL语句 

  1. 查看数据库: show databases;
  2. 使用数据库: use  数据库名;
  3. 创建数据库:create database 数据库名
  4. 查看数据库的表: show tables;
  5. 删除数据库 drop database 数据库名
  6. 删除表 : drop table t_student

创建一个sutdent表: 

create table t_student
(
-- 设置stuid为主键,自动增加
	stuid char(20) primary key auto_increment,
-- 设置约束不能为空
	stuname char(20) not null,
-- 设置约束stuage小于126大于0
	stuage int check(stuage<126 and stuage>0),
-- 设置stuphone 唯一
	stuphone char(11) unique,
-- 设置stusex 默认为男
	stusex char(4) default '男',
-- 自动获取系统时间
    writerDate TIMESTAMP  default CURRENT_TIMESTAMP 
-- 设置外键为 t_teacher.tid
	tid int references t_teacher.tid
);

创建一个teacher表

create table t_teacher
(
	tid char(20) primary key,
    tname char(20),
-- 设置联合主键
    primary key(tid, tname)
);

对数据库的基本操作

-- 插入
insert into t_student(stuid, stuname, stuage, stuphone, stusex, tid) values (1, '张三', 22, '15645663891', 'man', 10086)
 insert into t_student(stuid, stuname, stuage, stuphone, stusex, tid) values (3, 'ww', 22, '15689563891', 'man', 10086)
-- 删除
 delete from t_student where stuid = 3;
-- 查询
 select stuid ,stuname,stuage from t_student;
-- 修改
update t_student set stuname = '李奏' ,stuage = 16, stusex = '女' where stuid = 1;
-- 查询员工工资高于5000的员工姓名
select ename from emp where sal > 5000;

--  多个条件查询
-- 查询员工工资高于5000,同时奖金少于2W的员工
select ename from emp where sal > 5000 and comm < 20000

-- 查询员工工资高于5000,或者奖金少于2W的员工
select ename from emp where sal > 5000 or comm < 20000

--  模糊查询
-- 找出姓张的员工,%代表后面字符数>=0
select ename from emp where ename like '张%'

-- 找出姓张的员工,但名字总共只有两个字符,_代表后面字符数 ==1
select ename from emp where ename like '张_';

--  查询出员工的年薪 (表达式查询)
select sal * 12 + comm as totalSalary from emp;

-- 查询出员工名及其工资,格式如下:“张三:$1000”
select CONCAT(ename,':$1000', sal) from emp;

-- .函数查询 :统计函数 avg(), min(), count(), max() 
-- 计算公司员工的平均工资
select avg(sal) avgSalary from emp;
select sum(sal) sumSalary from emp;
select min(sal) minSalary from emp;
select max(sal) maxSalary from emp;
select count(*) avgSalary from emp;

-- 5. 分组查询 group by 分组查询select后面只能写group by 后面的字段
-- 求出每个部门的平均工资, 总工资
select deptno, avg(sal),sum(sal) from emp group by deptno;

-- where只能接字段名(列名)
-- 而having接统计函数
-- 6. 求出每个部门的平均工资,总工资,但只显示工资超过1W的部门
select deptno, avg(sal), sum(sal) from emp group by deptno having sum(sal) > 10000;

-- 7.限制记录的条数limit
-- 查询第五条到第七条数
-- 后面两个数字代表从哪个索引开始选,选择几条
select * from emp limit 4,3; 

-- 8.排序order by asc/desc 升序,降序
select *from emp order by sal asc;
select *from emp order by sal desc;

-- 找出工资最高的前三名
select *from emp order by sal desc limit 0,3

键的六大约束

  1. 主键 primary key    唯一的,不重复的,不能为空
  2. 非空 not null             这个不能为空必须填写
  3. 唯一 unique             不能重复,可以为空 
  4. 默认 default              不插入,则默认为默认约束
  5. 检查 check                检查数据合法性
  6. 外键                           将不想相关的表关联起来

猜你喜欢

转载自blog.csdn.net/qq_42651904/article/details/81332699
今日推荐