mysql基本使用语句 |
您所在的位置:网站首页 › dwl怎么删除 › mysql基本使用语句 |
基本命令
利用数据库 use 库名; 创建数据库 create database 库名; 创建表 create table 表名(字段 字段类型,id int,name varchar(32)); 显示数据库,表 show databases; show tables; 查看表的基本结构 describe 表名; 添加数据 insert into 表名(字段,id,name)values(值,1,“zl”); 修改数据 update 表名 set 字段=新值 where 条件; 删除数据 delete from 表名 where 条件; 注意:这儿的条件可以是范围,例如id>5..... 删除表 drop table 表名; 删除数据库 drop database 库名; alter修改命令修改表名 alter table 旧名 rename 新名; 修改字段名 alter table 表名 change 旧字段名 新字段名 新数据类型; 修改字段数据类型 alter table 表名 modify 字段名 数据类型; 修改字段的排列位置 alter table 表名 modify 字段1 数据类型 first | after 字段2; 添加字段 alter table 表名 add 新字段名 数据类型 [约束条件] [first|after] 已存在字段名; 删除字段 alter table 表名 drop 字段名; 删除字段的外键约束 alter table 表名 drop foreign key 外键约束名; 约束主键约束 定义列同时:id int primary key 定义列之后:primary key(id) 多字段联合主键:primary key(字段1,字段2) 外键约束 constraint 外键名 foreign key 字段名 references 主表名(主键名) 例如: CREATE TABLE t_dept ( deptId INT primary key, name VARCHAR(22), location VARCHAR(50) ); CREATE TABLE t_emp ( id INT PRIMARY KEY, name VARCHAR(22), deptId INT, CONSTRAINT fk_emp_dept1 FOREIGN KEY(deptId) REFERENCES t_dept(deptId) );常用约束 唯一约束:unique 非空约束:not null 默认约束:default ’值‘ 注意:值为字符串型使用单引号,为整型则不需要加任何符号;若加的是中文默认值,则需加上 default charset=utf8 例如:(不区分大小写) CREATE TABLE t_emp( id INT PRIMARY KEY, name VARCHAR(22) not null unique, sex VARCHAR(2) DEFAULT '男' ) DEFAULT CHARSET=utf8; 查询语句 单表查询:select *from 表名; select 字段1,字段2 from 表名; select 字段名 from 表名 where 字段名 in (n1,n2,n3);【括号内的数字必须为INT型】 select 字段名 from 表名 where 字段名 not in (n1,n2,n3);【除了括号中出现内容外的所有内容】 select 字段名 from 表名 where 字段名 between n1 and n2; select 字段名 from 表名 where 字段名 not between n1 and n2; select 字段名 from 表名 where 字段名 like "%"; select 字段名 from 表名 where 字段名 like "_"; 注意: 百分号通配符%:可以匹配任意长度的字符,甚至包括零字符 下划线通配符_:只能模糊匹配1个字符 select * from 表名 where 字段名 is null;【查询空值】 select distinct 字段名 from 表名;【去除重复结果】 select * from 表名 where 条件1 and 条件2;【多条件查询】 select * from 表名 where 条件1 or 条件2; select * from 表名 where 条件 order by 字段名 desc;【desc:降序,asc:升序】 select * from 表名 group by 字段名;【分组查询】 注意:一般情况下,group by都和聚合函数一起使用 select * from 表名 limit 偏移量,记录数; 例如: 查询班级中第2名到第5名的学生信息 select * from tb_score order by score desc limit 1,4; 连接查询:(1)内连接查询 语法:from 表1 join 表2 on 表1.字段名=表2.字段名 例如:
要求:查询数据表中学生姓名以及对应的班级名称,将其对应的列名分别另命名为studentName和className 代码:select tb_student.name as studentName,tb_class.name as className from tb_student join tb_class on tb_student.class_id=tb_class.id; 结果: (2)外连接查询 类型:左外连接查询和右外连接查询; 语法:表1 left/right [outer] join 表2 on 表1.字段=表2.字段(3)复合条件连接查询 举例:查询所有班级里分数在90分以上的学生的姓名和学生的成绩以及学生所在的班级,其中学生的姓名和学生所在班级分别另命名为studentName和className
代码:select tb_student.name as studentName,tb_student.score,tb_class.name as className from tb_student join tb_class on tb_student.class_id=tb_class.id where score > 90 order by tb_student.score desc; 结果:
声明:这里的例子出至于educoder.net 上面的《数据库原理与应用-MySQL从入门到实战》 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |