博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

MySQL基本操作--库\表增删改查

Posted on 2019-01-21 19:39  GraceNana  阅读(120)  评论(0编辑  收藏  举报
  • 库的增删改查

: create database db1;

: drop database db1;

: alter database db1 charset utf8; 修改库的字符集编码

: show database; 查看所有的数据库

show create database db1\G; 查看数据库创建信息

  • 表的增删改查

切换库: use db1     #要操作表文件,要先切换到对应的库下才能操作

: create table tb1(id int);

: drop table tablename;

(表字段的修改,表结构的修改):

Alter table xx rename  xxx

Alter table xx modify 字段名 数据类型 完整约束

                   Change 旧字段名 新字段名 数据类型 完整性约束

Alter table xx add 字段名 数据类型 完整约束 first;

                                                           after 字段名

Alter table xx add foreign key(c_id) references class(id);

: show tables;

  • 行记录操作

INSERT INTO 表名(字段1,字段2,字段3…字段n) VALUES(值1,值2,值3…值n)

: Delete from table_name where condition;

: Update tablename SET

     字段1 = value, …

      Where condition;

 单表查询: 

      Select * from    ①首先执行from

      Select distinct 字段1,字段2… From 库名.表明

      Where condition   ②执行

      Group by field(字段) (3)执行

      Having 筛选           ④再过滤

      Order by field(字段)     #将结果按照后面的字段进行排序

      Limit   限制条数  #将最后的结果加一个限制条数,就是要过滤或者说限制查询出来的数据记录的条数

 多表查询:

笛卡尔积:将两表的所有记录全部对应一遍

Select * from emp,dep where emp.id = dep.id;   获得一张虚拟表

连表操作

Inner join,left join(左表为主表) ,right join ,union(并集)

Select * from department 
inner join employee 
on condition1 
where condition2;

字段拼接

Select concat(‘姓名:’,name,’年薪’,salary) as info;

范围where

age between 18 and 40;age>=18 and age<=40;age>=18 or age<=40;

匹配like

Name like ‘a%’;  以a开头 (%模糊匹配)

Name like ‘%a’;  以a结尾

Name like ‘a_’;   以a开头向后匹配一个

Name not like ‘a%’ 不是以a开头,取反

… is null 判断某个字段是否为空

 子查询

select * from employee 
where id in
    (select id from department 
     where…);

where exists 如果存在则执行上述操作,作为判断条件使用