创建和操作表

2016-11-15  本文已影响0人  olivia_ong

创建表

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

引擎类型:

注:

AUTO_INCREMENT:

更新表

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 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 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 customers set cust_email='elmer@fudd.com'
where cust_id=10005;

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

update customers set cust_email=null
where cust_id=10006;

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

上一篇 下一篇

猜你喜欢

热点阅读