语法:
如果存在数据库删除数据库
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;
--查询数据
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')