DML语句 --- MySQL

  • SQL:结构化查询语言
  • DB:datebase 数据库

SQL语句主要有三个部分构成:DDL DML DCL
一、DDL:数据定义语言

二、DML:数据操作语言
(insert delete update select)
1、添加数据 insert

insert into stu values("001","zhangsan","man",20);
insert into stu(id,name, sex) values("002","lisi","woman");
//当添加数据与字段个数不匹配则要注明添加数据所对应的字段

小批量添加数据时,数据与数据中间加 “ ,”

insert into stu values("002","wangwu","man",22)("003","zhaosi","man",21);

2、删除数据 delete

delete from stu;
//所有数据都满足,即全部删除
delete from stu where id ="004";
//where加过滤条件,只删除id=004的数据 

3、修改数据 update

updeta stu set sex = "man";
//全部满足,将所有数据的sex修改为man
updata stu set age = 19 where id = "002";
//将id=002数据的年龄修改为19

4、查看数据 select

select * from stu;

【1】普通查询

select * from stu; #通匹配,代表所有字段,不建议(可能会造成信息泄露)
select id, name, sex, age from stu; #查询对应字段信息
select * from stu where id = "001";  #查询id=001的信息

【2】去重查询 distinct
eg:一款游戏,编号,姓名,性别,年龄
查询游戏用户的年龄范围

select distinct age from table_name;

【3】排序order by+要排序的字段 升序:asc 降序desc
(不注明排序的方法时,默认升序排序)

select distinct age from stu order by age;
select distinct age from stu order by age desc;  #降序排序

【4】分组查询 group by

常用聚合函数:

  • Sum 相加
  • count 统计数据条款
  • avg 计算平均数
    当用聚合函数是,过滤条件where应改为having
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    【5】连接查询
    在这里插入图片描述
    1、等值查询 (笛卡尔乘积的方法相乘匹配)
    效率低,不适合大数据
    //查询年龄小于20岁学生的不及格成绩
select id ,score from stu ,result where age < 20 and score <60;
//错误:id重复,不知道id是哪个表的id,id应改为stu.id

在这里插入图片描述

select stu.id ,score from stu ,result where stu.id=result.id and age < 20 and score <60;

注意 :两个表都有同一个字段时即该字段为主键时,查找时要先注明查找字段的表的来源(如:stu.id),后面过滤条件要加上两个表字段相同(stu.id=result.id)
在这里插入图片描述
2、连接查询 高效

  • 外连接查询

(1)左外连接:左表过滤的结果必须全部存在

select a.id,score
from
(select id,age from stu where age <20) a
left join
(select id,score from result where score < 60) b
on a.id = b.id;
#若要求右表字段不为NULL,则在结尾加where b.id is not null)

在这里插入图片描述
a:左表别名,前可加as也可省
b:右表别名
在这里插入图片描述
//将stu表中的004的age改为17,则结果为:
在这里插入图片描述
(2)右外连接查询:保证右表过滤的结果必须全部存在,
匹配失败,左表补空

select a.id,score
from
(select id,age from stu where age <20) a
right join
(select id,score from result where score < 60) b
on a.id = b.id;
#若要求左表字段不为NULL,则在结尾加where a.id is not null)

在这里插入图片描述
(3)全外连接查询:左表和右表的数据全部存在

select a.id,score
from
(select id,age from stu where age <20) a
full join
(select id,score from result where score < 60) b
on a.id = b.id;
#若要求左表字段不为NULL,则在结尾加where a.id is not null)

在这里插入图片描述

  • 内连接查询
select a.id,score
from
(select id,age from stu where age <20) a
inner join
(select id,score from result where score < 60) b
on a.id = b.id;

在这里插入图片描述
【6】聚合查询 union
教师表: 编号 姓名 性别 年龄

t01 yang man 18
t02 su man 17
t03 he man 17

学生表:编号 姓名 性别 年龄
//查询全校的师生信息

select * from stu union select * from teach;
发布了17 篇原创文章 · 获赞 4 · 访问量 1596

猜你喜欢

转载自blog.csdn.net/qq_43411866/article/details/104743082
今日推荐