1. 程式人生 > 其它 >mysql基礎初學(二)

mysql基礎初學(二)

DML語言(資料庫操縱語言)

  • 插入語句:
insert into 表名 (欄位1,欄位2,欄位3...) values ('值1','值2','值3',...)

--如果不寫表的欄位(欄位省略),值會一一匹配
insert into 表名 values('值1','值2','值3',...)

--插入多個值
insert into 表名 (欄位1,...) values ('值1',...),('值2',...)



示例:

--標準插入資料
insert into `student` (`id`,`name`,`pwd`,`sex`,`birthday`,`address`,`email`
) values(6,'chen',123456,'男','1998-10-18 10:44:55','廣東省','[email protected]') --省略欄位 insert into `student` values(1,'chen',123456,'男','1998-10-18 10:44:55','廣東省','[email protected]') --插入多個欄位 insert into `student` values(2,'chen',123456,'男','1998-10-18 10:44:55','廣東省','[email protected]'),(3,
'chenhui',123456,'女','1998-11-18 10:44:55','廣東省','[email protected]'),(4,'c',123456,'男','1998-12-18 10:44:55','廣東省','[email protected]')
  • 修改語句:
--指定條件修改
update 表名 set 欄位=where (欄位+條件)

--不指定條件的情況下,會修改表的所有值
update 表名 set 欄位=--修改多個屬性值,則用逗號隔開
update 表名 set 欄位1=,欄位2=where (條件)

示例:

--根據條件修改
update `student` set `name`='sss' where id between 2 and 4; --不指定條件修改表的所有值 update `student` set `name`='chen' ; --修改多個屬性值 update `student` set `name`='chen',`pwd`=66666 where `id`=1 or `id`=3 ;
  • 刪除語句:
--刪除指定條件資料
delete from 表名 where 條件

--刪除表的全部資料
delete from 表名

--刪除表的全部資料(推薦使用)
truncate table 表名

測試示例:

--刪除指定條件資料
delete from `student` where `id`=1

delete 和truncate刪除表資料的區別

  • 相同點:都能刪除資料,不會刪除表的結構
  • 不同點:truncate刪除表資料後會重置自增列,計數器會歸零;不會影響事務

測試示例:

  • 使用delete刪除表資料後:

刪除前:
在這裡插入圖片描述
刪除後新增一個數據檢視自增索引數:
在這裡插入圖片描述

insert into `student` (`name`,`pwd`,`sex`,`birthday`,`address`,`email`) values('chen',123456,'男','1998-10-18 10:44:55','廣東省','[email protected]')

在這裡插入圖片描述
總結:從上面可以看出,當表資料用delete刪除後,新增一條資料後,自增數並未重置為0,而是繼續自增

  • 使用truncate刪除表資料後
    刪除前:
    在這裡插入圖片描述
    刪除後,新增一個數據:
    在這裡插入圖片描述
insert into `student` (`name`,`pwd`,`sex`,`birthday`,`address`,`email`) values('chen',123456,'男','1998-10-18 10:44:55','廣東省','[email protected]')

在這裡插入圖片描述
總結:當用truncate刪除表資料時,自增數會重置為0

delete刪除問題也和資料庫引擎有關

當用delete刪除資料表資料時,重啟資料庫

  • InnoDB引擎: 自增數會重置,從1開始(即存在記憶體中,斷開即失)
  • MyISAM引擎:繼續從上一個自增量開始(即存在檔案中,不會丟失)