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

來源:互聯網
上載者:User

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

剛開始時碰到這個需求時,在網上搜尋了一下,發現都說不行,得先刪除那主鍵列再重新增加或者先建立一個暫存資料表再把資料導過來,其實在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 ;




用一個sql語句複製表中的所有行插入到表的後面(主鍵自增),在用一句sql語句重複資料刪除的行

例如表:student(id,name,sex.age),id主鍵自增
把表中紀錄複製再插入到這個表後面
insert into student select name,sex,age from student;
原則,除自增列外的所有列都要寫出,注意查詢欄位的順序和表對應,要不如下:
insert into student(sex,name,age) select sex,name,age from student;
查詢欄位和插入欄位對應

重複資料刪除的行
delete from student where id in (select a.id id from student a,student b where a.name=b.name and a.sex = b.sex and a.age=b.age and a.id<>b.id)
其中查詢語句為查出所有重複紀錄的id
select a.id id from student a,student b where a.name=b.name and a.sex = b.sex and a.age=b.age and a.id<>b.id
原則除主建外所有欄位都要相等
and a.id<>b.id ,這個不加就會把正個表的資料算重複
因為a和b都是student表,自己和自己比當然什麼都一樣,
and a.id<>b.id 就是和自己外的其他紀錄比

運行了,sql server2000的資料庫,沒有問題
你什麼庫
 
sql 表的主鍵是自增序列,怎解決刪除的id

給你一個觸發器,當你刪除一條,id遞減

create trigger delid
on 表名
for delete
as
begin
if @@rowcount=1
update 表名 set id=id-1 where id>(select id from deleted)
end

僅限刪除一行,如果刪除多行,請追分追問
 

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.