sql語言分為三個級別。
1、ddl
語句 ,數據定義語句,定義了數據庫、表、索引等對象的定義。常用語句包含:create、drop、alter。
2、dml
語句 ,數據操縱語句,用於添加、刪除、更新和查詢數據庫記錄,並檢查數據完整性,常用語句包含insert、delete、update、select等。
3、dcl語句,數據控制語句,用於控制不同數據對象訪問級別的語句。定義了數據庫、表、表、用戶的訪問權限和完全級別。常用的語句包括grant、revoke等。
DDL語句:
1、建庫、刪庫:
建庫:create database db名 default charset=utf8;
刪庫:drop database db名;
2、
表操作
2.1 建表1:
create table table_name(col1 type1 [not null] [primary key],col2 type2 [not null])
如:
create table person_info ( person_id smallint(5) unsigned auto_increment, name varchar(50) not null comment 'person_name', country varchar(60) default 'china', salary decimal(10,2) default 0.00 comment 'salary', primary key (person_id) )engine=innodb default charset=utf8;
括號外設置引擎與默認編碼
備注信息:comment
默認賦值:default關鍵詞
主鍵:一般放在最后。primary key person_id
引擎:engine innodb
備注信息:comment
默認賦值:default關鍵詞
主鍵:一般放在最后。primary key person_id
引擎:engine innodb
建表2:創建一個新表,與原表的表結構相同,但是並無數據。
create table table_nameliketable_name1;
2.2 修改表結構
alert table table_name MODIFY col_name column_definition [FIRST | AFTER col_name
]#修改字段類型
alert table table_name ADD col_name column_definition [FIRST | AFTER col_name
]#增加字段
alert table table_name DROP col_name
#刪除字段
alert table table_name CHANGE old_col_name new_col_name column_definition [FIRST|AFTER col_name
]#修改字段名
如:將country字段修改長度為50個字節,並放在salary字段后。以下兩種都可行。
alter table table_name
change
country
country
varchar(50)
default 'china'
after salary;
alter table table_name
modify
country varchar(50)
default 'china' after salary;
修改字段時,注意原有默認值,修改命令時默認值仍需要添加
2.3 查看表結構
desc table_name;
2.4 刪除表
drop table table_name;
插入語句:
insert into person_info(person_id,name,country,salary) values(1,'yu','china','2');#插入全部字段值,單條數據
insert into person_info(name) values('yu');#單條數據,只選插入的字段值。
insert into person(name) valuse('a'),('b');#同時插入多條數據
插入數據時,自增字段不需要添加,默認值可不輸入。