1. 程式人生 > 其它 >Mysql的建立、增刪改查

Mysql的建立、增刪改查

技術標籤:Mysql

文章目錄

1.建立表

語法:(不區分大小寫)

drop table if exists 表名; // 當這個表存在的話,刪除它
create table 表名(
	欄位名1 資料型別,
	欄位名2 資料型別,
	欄位名3 資料型別,
	...
);

//  欄位1是主鍵不為空  欄位名2(部分插入)不插入資料時預設為1
create table 表名(
	欄位名1 資料型別 primary key not null,
	欄位名2
資料型別 default 1, 欄位名3 資料型別, ... ); // unsigned:非負數,用此型別可以增加資料長度 auto_increment:自動遞增 create table if not exists 表名( 欄位名1 資料型別 unsigned auto_increment, 欄位名2 資料型別 not null, primary key(欄位名1) )ENGINE=InnoDB DEFAULT CHARSET=utf8;

engine=innoDB:將資料庫的引擎設定為InnoDB,從MySQL 5.6開始預設使用該引擎
default charset=utf8:設定資料庫的預設字元為utf8

欄位的資料型別

型別
int整數型
bigint長整型
float浮點型
char定長字串型
varchar可変長字串型
data日期型
BLOB二進位制大物件型:儲存圖片、視訊等流媒體資訊 Binary Large OBject
CLOB字元大物件型:儲存較大文字,比如,可以儲存4G的字串 Character Large OBject

1.1 char和varchar怎麼選擇

在實際的開發中,當某個欄位中的資料長度不發生改變的時候,是定長的,例如:性別、生日等都是採用char
當一個欄位的資料長度不確定,例如:簡介、姓名等都是採用varchar

1.2 表的複製

語法:

create table 表名 as
select語句; // 將查詢結果當做表創建出來 mysql> create table emp2 as select empno,ename from emp; Query OK, 14 rows affected (0.60 sec) Records: 14 Duplicates: 0 Warnings: 0 mysql> select * from emp2; +-------+--------+ | empno | ename | +-------+--------+ | 7369 | SMITH | | 7499 | ALLEN | | 7521 | WARD | | 7566 | JONES | | 7654 | MARTIN | | 7698 | BLAKE | | 7782 | CLARK | | 7788 | SCOTT | | 7839 | KING | | 7844 | TURNER | | 7876 | ADAMS | | 7900 | JAMES | | 7902 | FORD | | 7934 | MILLER | +-------+--------+ 14 rows in set (0.00 sec)

2. 新增資料

語法:

insert into 表名(欄位名1,欄位名2,欄位名3) values(1,2,3);

insert into 表名 values(1,2,3); // 順序需要按照表來,不能部分插入

insert into 表名(欄位名1,欄位名2,欄位名3) values(1,2,3),(1,2,3),(1,2,3); // 插入多行資料

 insert into dept1 select * from dept; // 將dept的查詢結果插入到dept1表中

欄位的數量和值的數量相同,並且資料型別要對應相同
寫部分欄位:當表中含的比insert的欄位和值時,其他欄位自動為null

3. 修改

語法:

update 表名 set 欄位名1=1,欄位名2=2... where 條件;

mysql預設提交事務

4. 刪除

語法:

delete from 表名 where 條件; // 根據條件從表中刪除資料

沒有條件全部刪除

4.1 刪除大表資料

truncate table 表名; // 表被截斷,不可回滾。永久丟失
drop table 表名; // 這個通用
drop table if exists 表名; // oracle不支援這種寫法

5. 查詢

簡單查詢

還有各種查詢,這裡不說了,之前講過