1.关于数据表的操作
查看所有表
show tables;
新建数据表
create table[if not exists] 表名
(
字段名1
列类型[属性][索引][注释],
字段名2
列类型[属性][索引][注释]
)engine myisam charset utf8;
查看数据表字段信息
desc 表名;
查看建表语句
show create table 表名;
查看数据表里的所有数据
select * from 表名;
2.增
往哪个表,哪几列里插入数据,可连续插入多行:(其中ignore的作用是如果数据存在,尤其是主键存在,就忽略插入)
insert ignore into 表名 (列1,列2,列3…)values(列1值,列2值,列3值…),(列1值,列2值,列3值…)…;
insert into 表名(列1,列2…) select 列1,列2…from 其它表名(注释:把其它表的列导入新表中)where…
3.改
改写哪个表,哪一行,哪一列:
update 表名 set 列1名=列1值 where 表达式;
4.删
删哪个表,哪几行:
delete from 表名 where 表达式
truncate 表名;
delete和truncate的区别:delete是逐行替换为空值,速度慢,容易恢复;truncate是直接删除行,速度快,难恢复;
5.主键和外键
主键:primary key
外键:创建表时,为了给字段增加约束(和其它表的字段联系起来,通过该相同字段将两个表关联起来,删除关联delete或者更新关联update):
constraint 索引名 foreign key(本表字段)references 外表(外表字段)on delete(或者update)cascade
以上代码代表:外表为主表,该表为子表。当主表字段改动时,子表字段也变动;
on delete set null:代表主表删除该字段行数据,子表设置为null
no action:子表有数据时,主表删不掉;先删除子表再删除主表
删除外键:alter table表名 drop foreign key 索引名;
增加外键:alter table 表名 add [constraint 索引名] foreign key(本字段) references 外表(外表字段);