插入数据:
insert into <table_name> ( field1, field2,...) values ( value1, value2,... );
修改表名:
alter table <table_name> rename <new_name>;
修改列类型:
alter table <table_name> modify <column_name> <字段类型>;
修改列名:
alter table <table_name> change column <column_name> <new_name> <字段类型>;
更新操作:
update <table_name> set <operation> where <condition>;
原因:设置set SQL_SAFE_UPDATES=0;
增加列:
alter table <table_name> add column <column_name> <字段类型>;
删除列:
alter table <table_name> drop column <column_name>;
添加主键:
alter table <table_name> add primary key(column_name);
添加外键:
alter table <table_name> add constraint <foreign_key_name> foreign key(column_name) REFERENCES <foreign_table_name>(column_name) (on update <cascade/set null/restrict> on delete <cascade/set null/restrict>);
其中最后括号中的部分为级联操作,update为主表中更新时对应操作,delete为主表中删除时对应操作:
1) cascade: 主表中更新或删除,对应表中也更新或删除;
2) set null: 主表中更新或删除,对应表中设为null;
3) restrict:主表中更新或删除,对应表中不执行相关操作。
如果括号中的部分省略,则默认执行restrict操作。
删除外键:
alter table <table_name> drop foreign key <foreign_key_name>;
1、创建外键时报错:errorno:121 cannot create table...
原因:外键的名字不能重复,和其他表的外键名字(foreign_name)不能相同
2、删除列时报错:errorno150
原因:删除的列是外键列,无法直接删除,需先删除外键再删除列
3、删除外键报错:errorno 152
原因:无法使用外键对应的字段名直接删除,需要使用外键名删除,所谓外键名是给外键设置的名字,在表属性中可以找到。
4、删除主表中数据报错:Error Code1451 cannot delete or update a parent row
原因:主表中有字段被设为其他表中的外键,解决方法为设置SET FOREIGN_KEY_CHECKS = 0。