数据库学习之SQL语句

数据库操作

查看所有的数据库

show databases;

进入数据库

use 数据库名;

创建数据库

create database 数据库名 default charset utf8;

查看当前使用的数据库

select database();

删除数据库

drop database 数据库名;

查看数据库的表

show tables();

表的操作

创建表

create table 表名 (列名1 数据类型,列名2 数据类型) engine=innodb default charset=utf8;

实例:
#创建表t1,id列为int类型,不能为空。且自增;name列为char类型,不超过10个字符
create table t1(id int not null auto_increment primary key,name char(10));

查看表的结构

desc 表名;

向表中添加内容(增)

insert into 表名(列名1,列名2) values('内容1''内容2') ;

删除表

drop table 表名;

删除内容(删)

delete from 表名 where 条件;

实例:
#删除表t1中id小于6的
delete from t1 where id<6;

清空表

#如果表中有自增,清空表之后,重新创建新表时,自增数据会接着之前的
delete from 表名;
#如果表中有自增,清空表之后,重新创建新表时,自增数据不会接着之前的
truncate table 表名;

修改表中内容(改)

updata 表名 set 条件 where 条件;

实例:#把表t1中年龄为17的改为18
updata t1 set age=18 where age=17;

查看表的内容(查)

#查询所有列
select * from 表名;
#查询指定列
select1,列2 from 表名;

as 关键字
使用as给字段起别名

select id as 序号,name as 名字 from 表名;

外键和主键

主键 :保证了数据的唯一性,一个表只能有一个主键,主键可以由多列组成。
外键 :保证了数据的完整性,用于与另一张表的关联。

constraint 外键名 foreign key("列名") references 另一个表的表名("列名"

排序

#默认从小到大排列
select * from 表名;
#根据id从大到小排列
select * from 表名 order by id desc;
#根据id从小到大排列
select * from 表名 order by id asc;
#按照学生年龄从大到小,id从小到大排列
select * from students order by age desc, id asc;

分组

group

#根据id进行分组
select * from students group by id;

对于聚合函数进行二次筛选时,必须使用having

#根据id进行分组并选择id大于1的
select count(id),name from students group by id having id>1;

条件语句查询

查询id大于3的学生

select * from students where id>3;

查询姓名不是小红的学生

select * from students where name != '小红';

查询id大于3的女同学

select * from students id>3 and gender="女";

查询id等于5或者名字叫小红的同学

select * from students id=5 or name="小红";

%表示任意多个任意字符
_ 表示一个任意字符

查询姓李的同学

select * from students where name like '李%';

查询姓李或者叫芳的同学

select * from students where name like '李%' or '%芳';

查询id是1或5或7的同学

#in表示一个非连续的范围
select * from students where id in(1,5,7);

查询id在3-9之间的学生

#between...and...表示一个连续的范围
select * from students where id in between 3 and 9;

分页

select * from 表名 limit start,count;

从start开始(默认值为0),获取count条数据

#查询1-3行的男生的信息
select * from students where gender="男" limit 1,3;

聚合函数

count(*) :表示计算总行数
max() :表示求此列的最大值

#求id这一列的最大值
select max(id) from students

min():表示求此列的最小值
sum():表示求此列的和
avg():表示求此列的平均值

Guess you like

Origin blog.csdn.net/qq_45701130/article/details/110563310