1. 程式人生 > >MySQL 增刪改查基礎

MySQL 增刪改查基礎

group by sum between let 建數據庫 drop null ret limit

終端登錄mysql:

  mysql -u root -p
  1111aaaa

創建數據庫:
  create DATABASE DBname;

刪除數據庫:
  drop DATABASE DBname;

創建數據表:
  create table student( `stu_id` INT UNSIGNED AUTO_INCREMENT,
    `stu_name` VARCHAR(8) NOT NULL,
    `stu_sex` CHAR(4),
    `stu_brethday` DATE,
    PRIMARY KEY(`stu_id`))
    ENGINE = InnoDB DEFAULT CHARSET = utf8;

  create table teacher_info (
    `t_id` INT UNSIGNED AUTO_INCREMENT,
    `t_name` varchar(8) NOT NULL,
    `t_sex` CHAR(4),
    `t_birthday` DATE,
    PRIMARY KEY(`t_id`))
    ENGINE = InnoDB DEFAULT CHARSET = utf8;

刪除數據表:
  drop table table_name;


-- 新增
  填寫部分字段信息插入
    INSERT INTO student(stu_name,stu_sex,stu_brethday)VALUES(‘張三‘,‘男‘,now());
  填寫所有字段信息插入
    INSERT INTO studentVALUES(‘5‘,‘張三‘,‘男‘,now());

-- 刪除
  delete from student where stu_sex is null;

-- 修改
  update student set stu_name = ‘張某某‘ where stu_name = ‘張某‘;

-- 查詢
  指定字段查詢
    select stu_name,stu_brethday from student;
  查詢所有字段
    select * from student;
  where條件查詢
    select * from student where stu_sex = ‘男‘;
    select * from student where stu_sex = ‘男‘ or stu_sex = ‘女‘;
    select * from student where stu_id between 1 and 3;
  limit字段
    select * from student limit 2;

  嵌套查詢
    select * from student where stu_id in (select t_id from teacher_info);
  ORDER BY 排序
    select * from student order by stu_id;
    select * from student order by stu_id desc;
  union 結果集合並
    select stu_name from student union select t_name from teacher_info;

  group by 分組
    select stu_name,sum(stu_id) from student group by stu_name;

  多表連接查詢
    內連接
      select * from student a inner join teacher_info b on a.stu_id=b.t_id;
    左連接
      select * from student a left join teacher_info b on a.stu_id=b.t_id;
    右連接
      select * from student a right join teacher_info b on a.stu_id=b.t_id;

MySQL 增刪改查基礎