创建和操作表

创建表

create table table_name
(
列名  数据类型  NULL/NOT NULL(指定值是否可为NULL)  DEFAULT 1(指定默认值,也可不指定)
...
PRIMARY KEY(主键名)
)ENGINE=...//指定引擎类型

引擎类型:

  • InnoDB:可靠的事务处理引擎,不支持全文本搜索
  • MyISAM:性能极高的引擎,支持全文本搜索,不支持事务搜索
  • MEMORY:功能等同于MyISAM,数据存储在内存,速度很快(特别适合于临时表)

注:

  • 不同的表可以使用不同的引擎
  • 外键不能跨引擎,即使用一个引擎的表不能使用不同引擎的表的外键

AUTO_INCREMENT:

  • 指的是本列没增加一行时自动增量,每个表值允许一个AUTO_INCREMENT列,而且它必须被索引
  • 确定AUTO_INCREMENT值
    select last_insert_id();

更新表

alter table table_name...
给表添加一个列:

alter table vendors
add vend_phone char(20);

删除刚刚添加的列

alter table vendors
drop column vend_phone;

删除表

drop table table_name;

重命名表

rename table backup_customers to customers,
backup_vendors to vendors;

在表中插入数据

  • 基本格式:insert into table(列名) values(值)
insert into customers
values(NULL,'Pep E. LaPew','100 Main Street','Los Angeles','CA','90046','USA',Null,Null);

更安全需要列出列名,可以只给指定的列提供值

insert into customers(cust_name,cust_address,cust_city,cust_state,cust_zip,cust_country,cust_contact,cust_email)
values('Pep E. LaPew','100 Main Street','Los Angeles','CA','90046','USA',Null,Null);
  • 插入检索出的数据
    insert into table_name(列名)select 列名 from 表;
    插入检索出的数据,将custnew表中的所有数据导入customers表中(列名可以不要求相同)
insert into customers(cust_name,cust_address,cust_city,cust_state,cust_zip,
cust_contry,cust_contact,cust_email,cust_id)
select
cust_name,cust_address,cust_city,cust_state,cust_zip,cust_country,cust_contact,cust_email,cust_id
from custnew;

更新和删除表中数据

  • 更新数据
    update 表名 set 列名=更新的值 where xxx(指定行);
update customers set cust_email='[email protected]'
where cust_id=10005;

即使发生错误也会继续更新:
update ignore 表名 set 列名=更新的值 where xxx(指定行);...

  • 删除数据
    删除某个列的值,即将其置为NULL:
update customers set cust_email=null
where cust_id=10006;

删除一行:
DELETE FROM 表名 where xxx(指定行);
DELETE语句如果删除表中所有行,并不删除表本身。
如果删除表中所有行,建议使用TRUNCATE TABLE语句,其速度更快,该语句是删除原来的表并重新创建一个表,而不是逐行删除表中的数据。

你可能感兴趣的:(创建和操作表)