注:博客中总结《MySQL必知必会》中的知识点,第19,20,21章的核心内容;
涉及到的操作符:INSERT INTO,UPDATE, DELETE,CREATE;
书中用到的表的介绍及其脚本文件:《Mysql必知必会》中表的介绍
也可以省略某些列行,但是需要满足这些列定义为允许NULL值,或者表定义给出默认值;
-- 这种语法简单,但是不安全,因为高度依赖表中列的定义次序;
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 customer
(
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'
)
INSERT INTO customer
(
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的使用要尽可能的小心,要遵循一些知道原则;
-- 不要省略WHERE,否则会改整列;
UPDATE customers
SET cust_email = '[email protected]'
WHERE cust_id = 10005;
-- 不要省略WHERE,否则会改整列;
DELETE FROM customers
WHERE cust_id = 10006;
-- DELETE是删除表中的行,甚至是表中所有行,而不是删除表本身;
DELETE FROM customers;
-- TRUNCATE TABLE 删除所有行,实际上删除原来的表并重新创建一个表,速度更快;
TRUNCATE TABLE customers;
CREATE TABLE customers
(
cust_id int NOT NULL AUTO_INCREMENT,
cust_name char(50) NOT NULL ,
cust_address char(50) NULL ,
cust_city char(50) NULL ,
cust_state char(5) NULL ,
cust_zip char(10) NULL ,
cust_country char(50) NULL ,
cust_contact char(50) NULL ,
cust_email char(255) NULL ,
PRIMARY KEY (cust_id)
) ENGINE=InnoDB;
-- 允许NULL值的列允许在插入行时不给出该列的值;
-- 不允许NULL值的列不接受该列没有值的行。
CREATE TABLE vendors
(
vend_id int NOT NULL AUTO_INCREMENT,
vend_name char(50) NOT NULL , -- 不允许NULL
vend_address char(50) NULL , -- 允许NULL
vend_city char(50) NULL ,
vend_state char(5) NULL ,
vend_zip char(10) NULL ,
vend_country char(50) NULL ,
PRIMARY KEY (vend_id)
) ENGINE=InnoDB;
-- 主键值必须唯一,主键可以是单列,也可以是多个列;
-- 在定义表时通过 PRIMARY KEY () 指定列;
例如:
CREATE TABLE orderitems
(
order_num int NOT NULL ,
order_item int NOT NULL ,
prod_id char(10) NOT NULL ,
quantity int NOT NULL ,
item_price decimal(8,2) NOT NULL ,
PRIMARY KEY (order_num, order_item)
) ENGINE=InnoDB;
cust_id int NOT NULL AUTO_INCREMENT,
-- AUTO_INCREMENT告诉MySQL,本列每当增加一行时自动增量。
-- 并且每行分配唯一的cust_id,从而可以作为主键;
使用DEFAULT指定;
CREATE TABLE orderitems
(
order_num int NOT NULL ,
order_item int NOT NULL ,
prod_id char(10) NOT NULL ,
quantity int NOT NULL DEFAULT 1,
item_price decimal(8,2) NOT NULL ,
PRIMARY KEY (order_num, order_item)
) ENGINE=InnoDB;
-- MySQL不允许使用函数作为默认值,它支持常量;
-- 添加新的列
ALTER TABLE vendors
ADD vend_phone CHAR(20);
-- 删除刚刚添加的列
ALTER TABLE vendors
DROP COLUMN vend_phone;
-- 删除整个表,而不是删除其中的行;
DROP TABLE customers2
RENAME TABLE customers2 TO customers;
-- 对多个表重命名
RENAME TABLE back_customers TO customers,
back_vendors TO vendors,
back_products TO products;