MySQL相关指令回顾

数据库的相关指令

1、建库:
drop database if exists 库名;#删除库
create database 库名;


2、建表:
drop table if exists 表名 #删除表
create table 表名(
列名 数据类型 是否为空 主键约束(primary key ) 外键约束(references 其他表(字段))  唯一约束、是否自增长,
)
eg:
create table student(
stuid int not null primary key references course(stuid) auto_increment,
stuname char(20),
stuage int,
CONSTRAINT student_n unique(classname)  #唯一约束,表示该列中不能重复,与外键的区别是可以为空
)auto_increment=100; #自增长的起始值

3、插入
insert into 表名(列名、列名、、、、)values(属性值、属性值、、、)
eg:
insert into student(stuid,stuname,stuage) values(1001,"张三",20);
或者:
insert into student values(1002,'李四'21);
具有自增长字段的还可:
insert into student(stuname,stuage) values("张三",20);

4、删除:
delete from 表名 where 条件
eg:
delete from student where stuid=1001;

5、查询:
基本查询:select * from 表名;
查询某个具体的数据:select * from 表名 where stuname='XXXX';
select * from student;
#查询年纪大于20或者小于18的学生信息
select * from student where age>20 or age <18;
#统计学生表总人数
select count(stuno) from student;
#输出学生表前十条数据
select * from student limit 10;
-- desc student;
#查询名字中第二个字为晓的学生信息
select * from student where stuname like "_晓%";
#统计班级表中的班级总人数
select sum(number) as 总人数 from class;
#统计住在洛阳性别为女的学生信息
select * from student where sex="女" and address="洛阳";
#删除18岁的男
delete from student where sex='男' and age=18;
#将所有大于21或者小于18 的男年纪修改为18
6、修改
update 表名  set 字段=新值 where +条件
eg:
#将所有大于21或者小于18 的男年纪修改为18
UPDATE student set age=18 where sex='男' and age>=21 or age<18;

7、连接条件查询
内连接 返回笛卡尔积 inner join
语法:select a.xxx,b.xxx from a inner join b on a.xxx=b.xxx(外键)
左连接以左表为准,无论右表是否有匹配的值,返回左表全部的值 left join
语法:select a.xxx,b.xxx from a left join b on a.xxx=b.xxx(外键)
右连接以右表为准,无论左表是否有匹配的值。返回右表全部的值 right join
语法:select a.xxx,b.xxx from a right join b on a.xxx=b.xxx(外键)

8、限制返回: limit
#输出学生表前十条数据
select * from student limit 10;
#输出学生表第三名的数据
select * from student limit 1 offset 2; #h忽略前两名 返回忽略后的第一名

9HAVING用法 与聚合函数共同使用时用having+条件
HAVING 子句可以让我们筛选分组后的各组数据
SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE 条件
GROUP BY column_name
HAVING 分组后数据满足的条件;
eg:
select 
emp_no,count(from_date) as t from salaries group by emp_no
having t>15;
#与聚合函数在一起时 必须用group by 分组 ,与聚合函数一起使用只能用having 加条件

猜你喜欢

转载自blog.csdn.net/HBT036017/article/details/109806887
今日推荐