Database command
Table Constraint
对表的列属性、column进行的限制。例如:not null、unique、primary key、foreign key、check。
1.create table,add the attribute constraints.
create table user(
id int,
name varchar(40) not null,
id_card varchar(20) not null unique,
phone_number varchar(11) not null,
age int(4),
class_id int(4),
constraint user_id_pk primary key(id),
constraint user_phone_number_uk unique(phone_number),
constraint user_class_id_fk foreign key(class_id) references `class`(id) ON DELETE CASCADE
)
the " constraint " is table level constraints , the " not null " is column level constraints。
2.add and remove table constraints, after the new table, can only add and remove constraint, cannot be modified
2.1 add constraints
alter table user add constraint user_age_ck check(age < 100);
2.2 add "not null" constraints
alter table user modify(age not null);
2.3 disable and enable constraints
-- disable constraint user_age_ck
alter table user disable constraint user_age_ck;
-- enable constraint user_age_ck
alter table user enable constraint user_age_ck;
Copy table or table data
copy table structure and data,but the destination table must not exist。
SELECT * INTO NEW_TABLE FROM OLD_TABLE;
注意:复制表的同时表的约定并不能复制过来。
如果是只复制表结构、不复制数据,只需要在where子句中添加一个永远不等于true的条件即可。
SELECT * INTO NEW_TABLE FROM OLD_TABLE WHERE 1 = 0;
Copy table data to a new table
INSERT INTO NEW_TABLE SELECT * FROM OLD_TABLE;
当表结构不同或复制部分字段可以设置插入相应的字段。例如:
INSERT INTO NEW_TABLE(name,age,address,phone) SELECT name,age,address,phone FROM OLD_TABLE;
Index
索引是一个设计用来提供整个数据库操作速度的数据库对象,它通过创建一个内部的索引表来达到快速搜索的目的。
索引可以降低insert、update和delete操作的性能,因为每次这些操作发生时,内部索引结构需要被更新(或者行被重新安排)。基于此原因,太多的索引会降低数据库的整体性能,因此要仔细调整。
当列被用于表连接或者与其它表有外键关系,并且列出现在where或者order by子句中时,在列上设置索引,是一个通用的技巧规则。
索引可以是唯一的和非唯一的。唯一索引不允许在索引列上出现重复值。
唯一索引通常创建在有主键或唯一约束的列上。
创建索引的关键字为create index,在其后要指明创建的索引的名称,在括号内列出索引表的字段(可以为多列)。
CREATE INDEX index_name ON table(column_1,column_2);
Create a non unique index
CREATE INDEX index_name ON table(column);
Create unique index,要添加unique关键字
CREATE UNIQUE INDEX index_name ON table(column);
Delete index
删除索引的SQL命令是drop index
DROP INDEX table_name.index_name;