MySQL插入数据、更新和删除数据、创建和操纵表
插入数据:
- 插入数据:
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_country) values('Pep E. LaPew', '100 Main Street', 'Los Angeles', 'CA', '90046', 'USA'), ('M. Martian', '42 Galaxy Way', 'New York', 'NY', '11213', 'USA');
- 从custnew中将所有数据导入customers:
insert into customers(cust_id, cust_contact, cust_email, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country) select cust_id, cust_contact, cust_email, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country from custnew;
更新和删除数据(使用update和delete时要小心谨慎,因为MySQL没有撤销按钮):
- 更新数据:
update customers set cust_name = 'The Fudds', cust_email = 'elmer@fudd.com' where cust_id = 10005;
- 为了删除某个列的值,可设置它为NULL:
update customers set cust_email = NULL where cust_id = 10005;
- 从customers表中删除一行:
delete from customers where cust_id = 10006;
创建customers表:
其中 AUTO_INCREMENT
表示该列的值自动增加。
MySQL具有多种引擎:InnoDB是一个可靠的事务处理引擎;MEMORY在功能等同于MYISAM,但由于数据存储在内存(不是磁盘)中,速度很快(特别适合于临时表);MYISAM是一个性能极高的引擎,它支持全文本搜索,但不支持事务处理。
主键再介绍,使用primary key(vend_id)
即可,例如:
更新表:
- 给vendors表增加一个名为vend_phone的列:
alter table vendors add vend_phone char(20);
alter table
的一种常见用途是定义外键:
删除customers 2表:drop table customers; 删除表没有确认,也不能撤销,执行这条语句将永久删除该表。
重命名表:rename table backup_customers to customers, backup_vendors to vendors, backup_products to products;