学习笔记-mysql增删改查操作语句

1.mysql增删改查操作语句:
1)如果想在一个已经建好的表中添加一列,可以用以下代码:
  alter table t1 add column addr varchar(20) not null;

2)这条语句会向已有的表t1中加入一列,这一列在表的最后一列位置。如果我们希望添加在指定的一列,可以用:
  alter table t1 add column addr varchar(20) not null after user1;
  注意,上面这个命令的意思是说添加addr列到user1这一列后面。如果想添加到第一列的话,可以用:
  alter table t1 add column addr varchar(20) not null first;

3)将表t1中,列名name改为firstname
  alter table t1 change name firstname char;

4)将表t1中,列名为def的列删除
  alter table t1 drop column def ;

5)复制table表
  create table 新表名(select ID,name,number,numberid from 要复制的表名);

6)查看表的各种数据类型
  describe `t1` 等同于 desc t1

7)查看表的已存数据
  select * from 表名  或  select id,name,number,numberid from 表名

8)添加数据
  insert into 表名 (ID,name,number,numberid) values(1,'mysql',220,1),(2,'HTML',160,1),(3,'python',230,1);

9)删除数据
  delete from 表名 where 条件;

10)修改数据
  update 表名 set numberid=2 where 条件

11)降序排列
  select id,name,number,numberid from 表名 order by id desc;

12)添加别名
  select (列名) '别名' ,(列名) as '别名' from 表名;

2.获取前10条数据:
  select * from t1 limit 10;

3.完全相同的数据,只更新第一条:
  update t4 set Id_O=1 where orderno=77895 order by Id_O desc limit 1;

4.修改表名(把t2修改成t3):
  alter table t2 rename to t3;

5.把t3表中重复的数据删掉只剩下一行:
1)先查询重复的数据:
  select * from t3 where OrderDate in (select OrderDate from t3 group by OrderDate having count(*) >1);
2)把重复的数据去重先保存到一张临时表中:
  create table tmp select distinct * from t3 where OrderDate in (select OrderDate from t3 group by OrderDate,O_Id having count(*) >1);
3)删除t3表中所有重复的数据:
  delete from t3 where OrderDate in (select t.OrderDate from (select OrderDate from t3 group by OrderDate having count(*) >1) t);
4)把处理后没有重复数据的tmp表中值重新放入到t3表中:
  insert into t3 select * from tmp;

6.在一个外部表中导入数据,由于某些原因第一次只导入了一部分,但很难判断具体位置,再接着导入所有数据后,怎样删除重复字段
1)添加自增列(first是在第一列添加):
  alter table t1 add column id int(11) primary key auto_increment first;
2)删除重复数据:
  delete from t1 where id not in (select tt.id from (select max(id) as id from t1 group by OrderDate,OrderPrice) as tt);
3)删除自增列id
  alter table t1 drop column id;

7.查询语句的灵活使用:
1)查询全部的记录:
  select * from t1 ;
2)查第一条记录:
  select * from t1 limit 1;
3)查前面两条记录:
  select * from t1 limit 0,2;
4)查第二和第三条记录:
  select * from t1 limit 1,2;
5)查最后一条记录:
  select * from t1 order by id DESC limit 1;

posted @ 2021-01-06 17:00  小鬼Tang  阅读(123)  评论(0)    收藏  举报