用SQL語句給乙個表的增加自增主鍵或刪除主鍵

2021-06-25 09:58:44 字數 636 閱讀 2611

剛開始時碰到這個需求時,在網上搜尋了一下,發現都說不行,得先刪除那主鍵列再重新增加或者先建立乙個臨時表再把資料導過來,其實在mysql中是可以直接修改的。

修改id欄位為自增主鍵:

alter table `test` change `id` `id` int (11) unsigned not null auto_increment , add primary key (`id` );

修改id欄位為自增非主鍵:

alter table `test` change `id` `id` int (11) unsigned not null auto_increment , drop primary key;

修改id欄位為普通字段:

alter table `test` change `id` `id` int (11) unsigned not null ;

另外,mysql5.1設定資料表分割槽時,primary key主鍵必須包含分割槽關鍵字,但如果分割槽關鍵字恰好不是主鍵的話,則只能把分割槽關鍵字加入到主鍵。還可以把主鍵取消同時保留該字段的自增屬性,但要有自增屬性的字段必須要建立索引(不需要是unique)。

但我一直搞不明白,為什麼主鍵必須前面的分割槽關鍵字,好像沒有必須存在的理由,難道是mysql公司為了他們方便實現分割槽演算法?

給乙個表增加列,重命表名

如何在表中增加新的列alter tabel table name add column name,dateype length alter table tablename1 add alter column fieldname1 fieldtype nfieldwidth nprecision nu...

用SQL語句獲得乙個儲存過程返回的表

定義乙個儲存過程如下 proc dbo test1 idint asselect1as id,abc asname union allselect idas id,zzz asname 返回兩行資料.現在想用sql語句來呼叫這個儲存過程,並把他返回的表放入變數中.可以如下做 declare tabl...

用SQL語句獲得乙個儲存過程返回的表

定義乙個儲存過程如下 create proc dbo test1 idint asselect1as id,abc asname union allselect idas id,zzz asname 返回兩行資料.現在想用sql語句來呼叫這個儲存過程,並把他返回的表放入變數中.可以如下做 decla...