操作MySQL数据库表单

一、创建数据库

语法:
如果存在数据库删除数据库
	drop database databaseName if exists databaseName;
如果不存在表创建表并设置编码方式
	create database databaseName if not exists databaseName character set utf8;

二、创建表

-- 创建表
drop table if exists tableName;
create table if not exists tableName(
	stuId int not null primary key auto_increment,
	stuName vahrchar(20) not null,
	stuSex varchar(4) not null,
	stuAge int not null,
	stuPhone varchar(20) not null,
	remark varchar(100)
);

三、复制表

不能复制主键,但是可以复制数据
	create table 表明 select * from tableName ;
能复制主键,但不能复制数据
	create table 表明 like tableName;
查看数据库表属性
	describle 表明;

四、修改表

添加字段
	alert table tableName add remark varchar(500)
删除表中字段
	alert table tableName drop remark;
修改字段属性
	alert table tableName change stuId id int not null primary key auto_increment;
给表单添加约束
	alert table s1 add primary key(stuId) 
修改表明
	alert table tableName rename to newTableName

五、添加数据

主键不能为空当赋值为0或者null时主键列auto_increment属性自动增长
添加数据的第一种方法
	insert into tableName values(0,'xiaoge','boy',18,'18386110976'); 
添加数据的第二种方法
	insert into tableName(stuName,stuSex,stuAge,stuPhone) values('xiaoge','boy',18,'18386110976');

六、批量新增

如果两个表单的结构相同可以同时添加多条数据
	insert into tableName select * from table name;

七、修改表单数据

修改表单数据
	update tableName set stuName='xiaoge',stuAge=18 where stuId=1;

八、删除数据

数据表不还原
	delete from tableName where stuId = 1 ;
数据表还原
	truncate table tableName;
	
delete 和 truncate 的区别:
    都可以删除表中的数据
    delete删除不会释放空间,truncate会释放空间
    truncate删除会很快
    对于自动增长列,delete删除后不会回到0,truncate删除将会从0开始自动增长

九、查询

--查询数据
select * from tableName; 查询所有数据
select stuName as '姓名' from tableName where stuId >=1 order by stuId desc;
select stuSex ,count(*) from group by stuSex having count(*) > 2; -- 分组查询,查询行数大于2条的数据
--限制行数limit ,limit 和SQLserver中的top相似
select * from table limit 3 -- 查询前三条数据
select * from table limit 3,5 -- 从第三条数据开始查询5条数据,相当于分页查询

-- 联合查询
-- 内连接查询
select * from tableName1 inner join tableName2 on tableName1.stuId = tableName2.stuId where 条件
select * from tableName1,tableName2 where tableName1.stuId = tableName2.stuId

--左链接 左边表显示所有数据 右边表显示关联的数据
select * from tableName1 left join tableName2 on tableName1.stuId = tableName2.stuId where 条件

-- 有链接 右边表显示所有数据 左边表显示关联的数据
select * from tableName1 right join tableName2 on tableName1.stuId = tableName2.stuId where 条件

-- 子查询 在查询中嵌入查询语句,一般在where后面当条件使用
select * from score where id in (select stuId from student where stuName = 'xiaoge')

select * from score where id exists(select stuId from student where stuName = 'xiaoge')

十、聚合函数

-- 聚合函数
count、sum、avg、max、min 
-- 数学函数
abs(number)  -- 绝对值
floor(float) -- 向下取整
ceiling(float)  -- 向上取整
round (3.1414151454,2) -- 四舍五入 保留2位小数
-- 字符函数
concat(’assd','aojfoi') -- 拼接
length(‘DVD水电费’) -- 长度
substring(string,index1,index)--截取string从index1下标开始截取index个
trim(‘’)-- 去掉首尾空格
replace(string,a,b)-- 使用a去替换string中b
new()  -- 当前时间

猜你喜欢

转载自blog.csdn.net/qq_43220836/article/details/106826336
今日推荐