作者小废话
最近小可爱可能发现了我的博客前面一部分重复了,这个是我特意这样写的,好处有三:
1.小可爱看到了可以再温习一遍,
2.小可爱可以根据这一部分找到自己的不足,也可以进一步分析sql语句
3.其实本人也有复习上一篇博客的习惯,这样写可以更加巩固上一天的知识
SQL增删改查
新增 、删除、修改数据
--增加数据 insert into 表名 (`字段名1`,`字段名2`)value('内容1','内容2'); --删除数据 delete from 表名 where 条件; --修改数据 update 表名 set `字段名`=内容 where 条件;
查询数据
表取别名
--方法1 select * from 表名 as 表别名; --方法2 select * from 表名 表别名;
查看某个字段
--方法1 select 表名.`字段名`from 表名; --方法2 select `字段名` from 表名; --方法3(注意一下,如果表取了别名,使用这个方法就必须使用表别名) select 表别名.`字段名` from 表名 as 表别名 ;
字段取别名
--方法1 select `字段名` as 字段别名 from 表名; --方法2 select 表名.`字段名`as 字段别名 from 表名; --方法3 select 表别名.`字段名` as `字段别名` from 表名 as 表别名;
查看前几行
select * from 表名 limit 数字;
去重
-- 方法1 select distinct * from 表名; -- 方法2 select distinct `字段名` from 表名;
条件
注意一下name 代表字段名 , table_name代表表名
比较运算符
-- 等于 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,但是可以加括号来优先
模糊查询
模糊查询一定是配合like使用
-- 下划线 _ 匹配任意一个字符 select * from table_name where name like '周_'; -- % 匹配任意多个字符 select * from table_name where name like '%周';
范围查询 in
-- 取id为1、4、10的人员数据 select * from table_name where id in (1,4,10); select * from table_name where id=1 or id=4 or id=10;
between and
-- between 取连续的数据 select * from table_name where id between 6 and 20; select * from table_name where id >= 6 and id <=20; -- 不同的数据库,sql中between的边界可能不同,有些是包头包尾,有些是包头去尾,或者是不包头也不 包尾
判断空
-- NULL select * from table_name where name is null; -- 非空 select * from table_name where name is not 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 = '男');
这里就不图片显示了,后面会有图片显示
union
上面所讲的查询都是查询一个表 的内容,如果同事查找多个表该怎么办,这就要利用到nuion了
在拼接过程UNION关联的两张表不在乎字段的名称是否相同。但是要求对应字段的格式和类型一致,而且字段的个数也要一致。
简单的理解为:
1.拼接两张表时,拼接的字段数要相同
2.拼接两张表时,拼接的字段所对应的数据类型要相同
int 和date不能相互转换,但是在mysql可以
--拼接显示前10行 select `id`,`name` from 表名 union select `zi`, `title` from 表名 limit 10;
distinct (去重)
其实union也自带去重效果,但在一些数据库中去重中要写distinct
select `id`,`name` from 表名 union distinct select `id`, `title` from 表名 limit 10
all: 返回所有结果集,包含重复数据。
1. select `id`,`name` from 表名 2. union all 3. select `id`, `title` from 表名 limit 10;