数据库的进阶操作

点我跳转到数据库的基本操作



数据库的进阶操作:

使用as给字段起别名

select 字段1 as 别名1,字段2 as 别名2 from 表名;

使用as给表起别名

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

消除重复行

select distinct 字段名 from 表名;

条件查找

select * from 表名 where 条件;

条件中加入判断

select * from 表名 where id<10;

常用的比较运算符

=, >, >=, <, <=, !=, <>等

逻辑运算符

and or not

模糊查询like

select * from 表名 where 字段 like 内容;
select * from students where name like %小_;
上例表示名字中倒数第二个字是小的人.%表示任意多个任意字符,_表示任一字符

范围查询

select * from 表名 where 字段 in(3, 8); 条件为3或8
select * from 表名 where 字段 between 3 and 8; 条件为3到8

多个条件

select * from 表名 where 条件1 and 条件2;

判断为空

select * from 表名 where 字段名 is null;

排序

select * from 表名 条件 order by 字段名 asc;
以某字段为标准排升序,desc为降序.不填默认为升序

分页查看数据

select * from 表名 条件 排序 limit a, b;
从第a+1条显示到第b条

聚合函数记总数

select count(*) from 表名 条件;
查询符合条件的行的数量

聚合函数查最大值

select max(字段名) from 表名 条件;
查询符合条件的行中,某字段的最大值.

聚合函数查最小值

select min(字段名) from 表名 条件;

聚合函数求和

select sum(字段名) from 表名 条件;
查询符合条件的行中,某字段的所有数据和

平均值

select avg(字段名) from 表名 条件;
查询符合条件的行中,某字段的所有数据的平均值

group by 分组

select 字段名 from 表名 group by 字段名;
按照某字段进行去重分组
注:以哪一字段分组,哪一字段可以直接查看.其他字段需用聚合函数查看或者中group_concat()查看

group_concat() 查看

select group_concat(字段2) from 表名 group by 字段1;

分组,并按条件查询

select 字段名 from 表名 group by 字段名 having 条件;
group分组后,条件查询要用having

with rollup

select 字段名 from 表名 group by 字段名 with rollup;
在显示出来的表后面增加一行来显示汇总信息

表与表链接

select * from 表1 inner或left或right join 表2 on 表1的某列=表2的某列;
inner表示内链接,显示两表共有数据,left表示左链接,显示左表所有数据

as起别名用于链接

select * from 表1 as a inner join 表2 as b on a.某列=b.某列;

自连接

select a.* from 表名 as a inner join 表名 as b on a.某列=b.某列;
自链接可以用来在一个比较复杂的表格中查询信息.

子查询

select * from 表名 where 列名 > (select avg(列名) from 表名);
查询数值大于平均值的某列
用另一个查询语句做参数的查询就叫做子查询.

子查询导入

insert into 表1(表1.字段名) select (表2.字段名) from 表2;
这种情况下插入,不需要用values

添加外键

alter table 表1 add foreign key外键名(字段) reference 表2(字段);

删除外键

alter table 表名 drop foreign key 外键名

猜你喜欢

转载自blog.csdn.net/washing1127/article/details/83543953