Mysql学习笔记--基础

一,SQL最重要的增删改命令格式

1,insert into 表名(不写这个括号里面的内容就默认所有字段都要添加) values() 插入单条数据

2,insert into 表名 (里面是列名) values(根据列名依次对应)()插入多条数据

删除

3,drop table 表名 删除表 删除数据库drop database 数据库名;

4,delete from 表名 where 条件 删除表中的数据一行的内容

5,alter table 表名 drop 字段名/约束 删除字段/约束

改,更新

6,rename 表名 to 新表名 更改表名 /alter table 旧表名 rename to 新表名

9,alter table 表名 change 旧字段名 新字段名 字段类型 约束

7,alter table 表名 modify 字段名 值 类型 约束

10,alter table 表名 add 字段名 类型 往表中添加字段

8,update 表名 set 字段=新值,字段2=新值 where条件 更改表数据

二,查询的基础知识

1,简单查询(快捷输入selw)

select 字段名 from 表名 where 条件

查询时可以对字段进行处理

select cid+1 from mytable where cname='家电';

distinct 对查询的字段名进行去重处理

select distinct cname from mytable ;

2,模糊查询(_表示占一位,%匹配任意多个字符)

select * from user where cname like '_字%'

③非空查询 is null或is not null

select *

from mytable

where desc is null;

3,排序查询asc升序,desc降序

select *

from mytable

order by(cid) desc ;

同时对多个字段进行排序,当第一个排好了之后才对第二个进行排序

select * from mytable

order by cid desc ,cname desc;

4,聚合查询

count()统计指定列不为null的记录行数 select count(distinct cname) from mytable; 去重查询

sum()求指定列数值的总和

avg()求平均价格

max() ,min()最大,最小select max(cid),min(cid) from mytable;

5,分组查询(相同的可以分成一组)(where后面不能跟聚合函数)

分组的字段可以有多个,根据多个查询后,having可以进行条件判断

select *

from mytable

group by sex,desc having sex='男';

6,分页查询(limit m,n;参数意思,索引值从0开始,查询5条数据)

select * from mytable limit 0,5;

表示从第0条数据开始1,每页查询5条数据

7,多表查询

内连接 select 字段,字段 from 表a inner/left/right join 表b on a.字段 = b.字段

select * from mytable inner join student s on mytable.cid = s.cid

内连接,左连接,右连接

基本区别:

8,外键约束

constraint foreign 从表(从表字段名) references 主表(主表主键)

例如:向表中添加主键约束

创建表后,使用alter table关键字添加主键 alter table 表名 add primary key(字段名);

删除主键约束 使用alter table关键字删除主键 alter table 表名 drop primary key;

例如:向表中添加外键约束

alter table 表名 add foreign 从表(从表字段名) reference 主表(主表主键字段)

注意:

当从表插入数据时,如果连接字段主表没有,则会报错(插入数据时,需要根据主键字段名来插入对应的值)

当删除主表主键字段时需要先删除从表中对的该字段,不然会报错。

9,case when 语法

case

when 条件判断 then条件成立,返回的值

when 条件判断 then条件成立,返回的值

else 返回的值

end as 别名

复制代码
# 根据判断条件创建新的字段,拥有几个when就会分成多消耗类
select product_name,product_id,
case
    when units_in_stock>100 then '高'
when units_in_stock between 50 and 100 then '中'
    when  units_in_stock between 10 and 50 then  '低'
    else '无法判断'
END  AS nun
from  products
order by nun desc;

2,case when之后根据起的别名进行分组,更方便

3,case when和count(),将case when放入coutn()里面进行判断

相关推荐
会飞的灰大狼2 小时前
MyCAT完整实验报告
mysql·centos7
饕餮争锋3 小时前
设计模式笔记_行为型_访问者模式
笔记·设计模式·访问者模式
不羁。。5 小时前
【撸靶笔记】第七关:GET - Dump into outfile - String
数据库·笔记·oracle
python_chai7 小时前
从数据汇总到高级分析,SQL 查询进阶实战(下篇)—— 分组、子查询与窗口函数全攻略
数据库·sql·mysql
好望角雾眠10 小时前
第一阶段C#基础-10:集合(Arraylist,list,Dictionary等)
笔记·学习·c#
艾伦~耶格尔10 小时前
【集合框架LinkedList底层添加元素机制】
java·开发语言·学习·面试
星仔编程10 小时前
python学习DAY46打卡
学习
冒泡的肥皂10 小时前
MVCC初学demo(一
数据库·后端·mysql
大霞上仙10 小时前
实现自学习系统,输入excel文件,能学习后进行相应回答
python·学习·excel
yatingliu201912 小时前
HiveQL | 个人学习笔记
hive·笔记·sql·学习