alter
table stu modify name varchar(20
)unique
;#改變表中狀態,給表去加個約束
desc stu;
#檢視表的結構
#唯一約束,人稱唯一索引,想要去除唯一約束需要
alter
table stu drop
index name;
#去除掉唯一索引
#但是增加唯一索引可以用modify方式增加
alter
table stu modify name varchar(20
)unique
;desc stu;
#建立表的時候也可以增加約束
create
table stu (
id int
, name varchar(20
)not
null
#不能為null的索引);
alter stu modify name varchar(20
);#直接用修改的手段可以進行修改
alter
table stu modify id int
primary
key;
#新增主鍵,整個表裡只有乙個主鍵,主鍵是唯一的
alter
table stu drop
primary
key;
#刪除主鍵,主鍵是唯一的,所以並不需要標識
主鍵約束中的自動增長
alter
table stu modify id int
primary
keyauto_increment
;#auto_increment和主見一起使用,實現自動增長
select
*from stu;
insert
into stu(id,name)
values(1
,"bba");
insert
into stu(id,name)
values
(null
,"bba");
#加入了自動增長後會跟隨上一條記錄進行自動增加
#建立表時候新增,外來鍵,增加兩個表的耦合
#一般來說外來鍵列,關聯的都是另外一表主鍵列
#create table stu ( ...
# ...
# id int 外來鍵列 和外部進行耦合的乙個列
#語發 constraint 外鍵名車 foreign key 外來鍵列名 references 主表名(主鍵列名)
create
table smm(
id_job int
, age int
, father varchar(20
),constraint smm_stu foreign
key(id_job)
references stu(id)
)#讓表與表之間有關係,保證正確
alter
table smm drop
foreign
key id_job;
#新增外來鍵
alter
alter smm add
constraint smm_stu foreign
key(id_job)
references stu(id)
;#修改表的外來鍵約束
select
*from stu;
sql中外鍵連線兩個表的約束
1.cascade 使用聯級刪除(on delete cascade),在外鍵約束時新增
被外來鍵連線的兩個部分都被刪除
2.no action 關聯部分被刪除後不做任何事情
3.restrict,表示約束,不讓刪
4.set null
sql中的一些通用函式
1.sql中使用case,when,then select case type when 1then 正常 when 2then 密碼錯誤 else 不正常 end 狀態 from tbl user 或者select case when type 1then 正常 when type 1then 密...
SQL學習中的一些疑問(一)
all 對所有資料都需要滿足條件,整個條件才會滿足 any 只要有一條資料滿足條件,整個條件成立 some 與any等同。注 在比較數字時,使用max min可能效率會更高。今天使用的是mysql 5.7,在直接使用sql插入資料事,報了上述錯誤,最後發現原因是,對於現版本來說,需要將時間精確到秒 ...
索引的一些jingyan
為什麼要加索引?提高查詢效率 類似乙個字典裡 新增了目錄 索引的分類 一 普通索引 二 唯一索引 可以是組合索引。索引可以是空,必須唯一,不一定是主鍵 三 全文索引 一般用在搜尋文章內容,避免用like 四 組合索引 最左字首 比如乙個組合索引是title 50 time 10 這時where條件中...