MySQL数据库第七课————数据的增删改查----------简单操作

作者前言

 欢迎小可爱们前来借鉴我的gtiee秦老大大 (qin-laoda) - Gitee.com

——————————————————————————————

目录

SQL增删改查

        新增数据

        删除数据

        修改(更新)数据

查询数据

        条件

————————————————————————————————

插播小知识

1.我们在创建表格时,主键的单个字段不要设计not null,

SQL增删改查

新增数据
insert into 表名(`字段1`,`字段2`..........)value(内容1,内容2,....);

删除数据
delete from 表名 where 条件;

# 删除,从哪个表删除

建议使用上面那条

DELETE FROM table_name WHERE 删除的条件
-- 如果没有写where条件,表中的数据将被全部删掉
-- 清空表数据,表的结构、索引、触发器、约束等将被保留,后续仍然可以使用该表
TRUNCATE TABLE table_name
-- 使用TRUNCATE TABLE,消耗的资源更少,比DELETE FROM要快

扫描二维码关注公众号,回复: 15677172 查看本文章

修改(更新)数据
update 表名 set  `字段名`=写改成的内容,.... where  条件;

如果不写条件就会修改该字段的全部内容,如果是修改字段的空值内容,要使用  字段名 is null,不能使用字段名=null

 查询数据

-- 使用星号(*)来代替其他字段,SELECT语句会返回表的所有字段数据
SELECT * FROM table_name;
select * from 表名;
--查看前10行数据
select * from 表名 limit 10;

 如果想查看哪个字段的数据可以这样写

select 字段名1,字段名2,... from 表名;

当我们查看数据的时候,可能会出现这个表格名太长,字段名不好区分,那我们就给这些取别名

表取别名
--表取别名
select  * from 表名 as 别名;或者select  * from 表名  别名
--没取别名,我们可以这样写
selete  表名.`字段名`  from 表名;




--取了别名
selete 表别名.`字段名` from  表名 as 表别名

注意一下如果要按照这种写法的话,在给表取了别名一定要使用别名,否则会报错

而字段取别名就会比较简单

再者 ,表能取别名,那字段也能取别名

select `字段名` as `别名` from  表名;
select   表别名.`字段名` as 字段别名   from  表名  as表别名;

数据去重
select distinct  `字段名` from 表名;

 注意一下,这里这是查询,不是修改原来的数据啊

条件
使用 where 子句对表中的数据筛选,满足 where 后面条件的数据会被查询出来
where 后面支持多种判断,进行条件处理
比较运算符
-- 等于
select * from table_name where id = 3;
-- 大于
select * from table_name where id = 3;
-- 大于等于
select * from table_name where id >= 3;
-- 小于
select * from table_name where id < 3;
-- 小于等于
select * from table_name where id <= 3;
-- 不等于
select * from table_name where id != 3;
select * from table_name where id <> 3;
逻辑运算符
-- 与
select * from table_name where id > 3 and gender = '男';
-- 或
select * from table_name where id > 3 or gender = '男';

注意一下当我们写了多个and 和or无法判断运行or还是and,我们可以加括号

加括号先执行,或者and的优先运行

模糊查询

模糊查询一定是配合like使用

-- 下划线 _ 匹配任意一个字符
select * from table_name where `字段名` like '周_';
-- % 匹配任意多个字符
select * from table_name where `字段名` like '%周';

  

in()
select *from 表名 where `字段名`in();

这是一种写法,in这种写法跟and的写法有像,但是有差别,使用in只会找到in里的数据,相当于一个枚举 

between  and

相当于闭区间

比如 between 20 and 30 ------>[20,30]

select * from new_employees where `age` between 65 and 70 limit 10;

判断空  (使用is)
 select *from new_employees  where `last_name` is null limit 10;

 null不是 '' null是数据没有填,'' 表示空的字符串。不能使用 = NULL != NULL 在列中查找 NULL  因为有些人会写null充当数据,或者敲个空格,当我们排除数据就会很难,所以就有了这个 `字段名`is null

优先级
-- 当无法判断条件运行的优先时,可以使用小括号
select * from table_name where id > 10 and name is null or gender = '男';
select * from table_name where id > 10 and (name is null or gender = '男');

总结:

时间很快就过去了,我介绍的sql的增删改查暂时到这里了,有不明白的小可爱可以私聊我

猜你喜欢

转载自blog.csdn.net/m0_69984273/article/details/131692598