常用管理SQL语句之表操作

  • Post author:
  • Post category:MySQL
  • Page Views 427 阅读

1.建表

create table table_name(
<字段名1> <类型名1>
...
<字段名n> <类型名n>
);

例子:
1.​人工设计的建表语句
create table table_name(
id int(4) not null,
name char(20) not null,
age tinyint(2) not null default ‘0’
);
2.mysql生成的建表语句
create table `table_name`(
`id` int(4) not null,
`name` char(20) not null,
`age` tinyint(2) not null default ‘0’
);

2.查看表结构

desc table_name;
show columns from db_name.table_name;
show full columns from table_name from db_name;

3.更改表名

rename table 原表名 to 新表名;
alter table 原表名 rename to 新表名;

4.增加表字段

alter table table_name add 字段 类型 其他;

例:
alter table test add sex char(4);
alter table test add sex char(4) after name;
alter table test add sex char(4),add sex char(4) after name; #同时增加多个字段以逗号隔开

5.删除表字段

alter table 表名 drop 字段名;

6.修改表字段

alter table test modify sex int(4) after name;   #修改字段类型
alter table test modify sex sex1 int(4) after name; #修改字段名称

7.删除表

drop table table_name;

8.往表中插入数据

insert into 表名(字段名1...字段名n) values(值1...值n);

例:
insert into test(id,name) values(1,study);
insert into test values(1,study); #如果不指定列,则按规则为每列都插入恰当的值
insert into test values(1,study),(2,other); #批量插入值

9.查询表数据

select <字段1,字段2...> from <表名> where <表达式>;


select * from test;
select * from db_name.test; #库外查询
select * from test limit 2; #查询前两行
select * from test limit 0,3; #查询记录范围
select age from test where age=’18’; #查询条件
select age from test where age=’18’ and name=’zhangsan’;
select age,name from test where age>18 and age<20;
select age,name from test where age>18 order by age asc; #查询排序(desc)

​10.修改表数据

update 表名 set 字段=新值,... where 条件;


将id为1的name字段值改为lisi
update test set name=’lisi’ where id=1;

11.删除表数据

​​​​delete from 表名 where 表达式;
truncate table 表名; #清空表数据


「 文章如果对你有帮助,请点个赞哦^^ 」 

0