天天看點

<導圖>Mysql入門基礎文法及示例

資料庫操作

檢視所有資料庫

  • show database;

建立資料庫

  • 文法
    • create database 資料庫名 charset=utf8;
  • 示例
    • create database school_of_three_kindoms charset=utf8;

使用資料庫

    • use 資料庫名;
    • use school_of_three_kindoms;

檢視目前使用的資料庫名稱

  • select database();

删除資料庫

    • drop database 資料庫名;
    • drop database school_of_three_kindoms;

資料表操作

檢視目前資料庫中所有表

  • show tables;

檢視表結構

    • desc 表名;
    • desc students;

建立表

    • create table 表名稱();
- -- 建立學生基本資訊表  
      create table students(  
        -- 學籍号:int unsigned無符号整型, auto_increment自增,primary key設定為主鍵,not null非空   
        id int unsigned auto_increment primary key not null,  
        -- 姓名: varchar(30)可變字元類型, default ""預設為空字元  
        name varchar(30) default "",  
        -- 年齡: tinyint unsigned無符号整型, default 0 預設為 0  
        age tinyint unsigned default 0,  
        -- 身高: 浮點型(5個數字,包含2個小數,如 180.05)  
        height decimal(5, 2),  
        -- 性别: enum枚舉類型("1"對應"男","2"對應"女","3"對應"保密"")  
        gender enum("男","女","保密"),
      );
           

修改表中字段

  • 添加字段
      • alter table 表名稱 add 新增字段名稱 新增字段的屬性;
      • alter table students add is_delete bit default 0;

  • 修改字段
    • 重命名字段
        • alter table 表名 change 原字段名 新字段名 新字段的屬性;
        • alter table students change name new_name varchar(30) default "";

    • 修改字段屬性
        • alter table 表名 modify 字段名 字段的屬性;
        • alter table students modify name varchar(30) default "";

  • 删除字段
    • alter table students drop age;

删除表中字段

    • alter table 表名稱 drop 表中字段;
    • alter table students drop age;

其它

  • 更改表的名稱
      • alter table 原表名稱 rename to 新表名稱
      • alter table students rename to super_students;

  • 檢視表的建立語句
      • show create table 表名
      • show create table students;

資料操作(CURD操作)

insert into | 建立(增)Create

    • insert into 表名 values (各字段的值);
- insert into students values  
        (null, "曹操", 50, 183.05, 1),  
        (null, "夏侯惇", 40, 193.05, 1),  
        (null, "許褚", 42, 186.05, 1);
           

update set | 更新(改)Update

    • update 表名 set 字段名 = 值 where 條件
    • update students set age = 51 where id = 5;

select from | 讀取(查)Retrieve

  • 查詢表内全部資訊
    • 格式
      • select * from 表名稱;
      • select * from students;

  • 查詢特定字段
      • select 字段1, 字段2 from students;
      • select id, name from students;

delete from | (删除記錄)Delete

  • 實體删除
      • delete from 表名[where條件判斷]
      • delete from students where id = 4;

  • 邏輯删除
    • 本質是修改操作,将實作設定好bit類型的字段值改為”非預設值”,用于和未删除的值做區分;

sql語句入門導圖