mysql常用语句合集

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_39532362/article/details/87438136

基本语法

show

show databases;

show tables;

show columns from tbl;

show create table tbl;

show table status like 'tbl'\G;

创建

create database dbn;
use dbn;

create table tbl(
  id int unsigned auto_increment, 
  name varchar(40) not null default '', 
  age int not null default '0', 
  primary key (id,age)
);

插入

insert into tbl (name,age) values ('mark',18),('zzz',19);

删除

drop dbn;

drop table tbl;

delete from tbl where id=1;

修改值

update tbl set name='jone' where id=1;

查询数据

select name,age from tbl where binary id=1;
select * from tbl where name like '%k';
select * from class1 where name is not null;

排序

select * from tbl order by id;

链接

select class1.id,class1.name,class2.name from class1 inner join class2 on class1.id=class2.id order by class1.id; 

alter

# 修改表存储机制
alter table class1 engine=innodb;
# 修改字段名
alter table class1 rename to class3;
# 修改字段名及数据类型
alter table class1 change score score2 int;
# 添加字段
alter table class1 add score int after name;
# 删除字段
alter table class1 drop score2;
# 修改字段数据类型及声明
alter table class1 modify score carchar(20) not null default '100';
# 修改字段default设置
alter table class1 alter score2 set default 100;
# 删除字段default设置
alter table tbl alter score2 dorp default;
# 添加主键
ALTER IGNORE TABLE person_tbl ADD PRIMARY KEY (last_name, first_name);
# 修改主键
alter table class1 add id int unsigned not null auto_increment first,add primary key(id),auto_increment=100;

函数

# 返回btl的行数
select count(*) from tbl
# 返回precol的链接字符串表 
select concat('pre',col1) from tbl
# 把tbl某列链接为字符串,以逗号分隔
select group_concat(col order by col desc separator ',') from tbl

例子合集

克隆表

create table clone_tbl;
insert into clone_tbl (id,name) select id,name from tbl;

删除数据库所有表的语句表

  • 将查询结果用excle导出,放在数据库执行
SELECT CONCAT('drop table if exists ',table_name,';') FROM information_schema.`TABLES` WHERE table_schema='mysql';

删除数据库以help_的表的语句表

SELECT CONCAT('drop table ',t.`TABLE_NAME`,'; ') FROM information_schema.`TABLES` as t WHERE t.`TABLE_NAME` LIKE 'help_%' and t.`table_schema`='mysql';

获取表的所有列名

select COLUMN_NAME from information_schema.COLUMNS where table_name = 'your_table_name' and table_schema = 'your_db_name'; 

删除重复数据

CREATE TABLE tmp SELECT last_name, first_name, sex FROM person_tbl  GROUP BY (last_name, first_name, sex);
DROP TABLE person_tbl;
ALTER TABLE tmp RENAME TO person_tbl;
delete from test1 where id in 
(select id from	
(select * from test1 
where userid in (select userid from test1 group by userid having count(*)>1) 
and fanid in (select fanid from test1 group by fanid having count(*)>1) 
and id not in (select min(id) as id from test1 group by userid having count(*)>1)) as tmp);

猜你喜欢

转载自blog.csdn.net/weixin_39532362/article/details/87438136