Database command

Database command

Table Constraint

  对表的列属性、column进行的限制。例如:not null、unique、primary key、foreign key、check。sql

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 modifiedspa

2.1 add constraints设计

alter table user add constraint user_age_ck check(age < 100);

2.2 add "not null" constraintscode

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; 

注意:复制表的同时表的约定并不能复制过来。rem

若是是只复制表结构、不复制数据,只须要在where子句中添加一个永远不等于true的条件便可。io

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;
相关文章
相关标签/搜索