MySQL復習筆記I
[sql]
#查看包含哪些數據庫
show databases;
#使用名為 test 的數據庫
use test;
#最簡單的(tinyint 默認是 3 個字節,但可以顯式地指定為 1 個字節;unsigned 須跟在後面)
create table tb0 (
id int not null,
name char(20),
age tinyint(1) unsigned default 0
);
#帶主鍵的
create table tb1 (
id int not null primary key,
name char(20)
);
#復合主鍵
create table tb2 (
id int not null,
name char(20),
primary key (id, name)
);
#帶默認值的(check只是個擺設,mysql會直接忽略之)
create table tb3 (
id int not null default 0 primary key,
name char(20) default '1',
sex char(1) not null check(sex in ('M', 'F')),
age tinyint not null check(age >= 0 and age < 100)
);
#插入記錄
insert into tb3(id,name,sex,age) values(1,"",'M',99);
insert into tb3 values(2,"haha","F",888);
insert into tb3 values(3,"bruce.yang","A",23);
insert into tb3(id,sex,age) values(4,'M',123);
#自增長主鍵(auto_increment 和 default 沖突)
create table tb4 (
id int not null auto_increment primary key,
name char(20) default 'hahaha'
);
#插入記錄
insert into tb4(id,name) values(888,"huhuhu"); #記錄id為888
insert into tb4(name) values('bruce.yang'); #記錄id為889
insert into tb4(id,name) values(1,"hello"); #記錄id為1
insert into tb4(name) values("xixi"); #記錄id為890
#使用 test 數據庫
use test;
#刪除 test 數據庫中得 tb0 表
drop table tb0;
#在刪除表的過程中,如果刪除一個不存在的表將會產生錯誤,
#這時在刪除語句中加入 IF EXISTS 關鍵字,就可避免產生錯誤,具體格式如下:
drop table if exists tb0;
#注意:
#在執行 CREATE TABLE、ALTER TABLE 和 DROP TABLE 中的任何操作時,
#首先必須要選擇好數據庫,否則是無法對數據表進行操作的
#查看表結構
desc tb4;
#刪除記錄(id 為 890 的記錄刪除以後,新插入記錄的 id 將會從 891 開始)
delete from tb4 where id=890;
#更新記錄(主鍵字段的值也可以更新)
update tb4 set id=892 where id=891;
update tb4 set id=893,name="9lala" where id=892;