CREATE TABLE
CREATE TABLE IF NOT EXISTS
customers (
customer_id INT (11) NOT NULL AUTO_INCREMENT,
#自增長光羞;
customer_name VARCHAR (20) NOT NULL,
customer_age TINYINT (2) NULL,
customer_city VARCHAR (10) NULL,
customer_tel VARCHAR (20) NOT NULL,
PRIMARY KEY (customer_id) #customer_id被定義為主鍵酪耕;
) ENGINE = INNODB;
使用IF NOT EXISTS來判定表是否存在,如果存在則不進行創(chuàng)建;
每個表只能有一個AUTO_INCREMENT;
SELECT LAST_INSERT_ID()
查詢最后插入的id值稳捆,適用于查詢自增主鍵值火的;
但是對于批量插入和單個插入的值返回會有區(qū)別壶愤,具體見下面的例子:
INSERT INTO customers (customer_name,customer_tel) VALUES('張學友','13568898321'),('郭富城','15927944212')
SELECT LAST_INSERT_ID()#1
INSERT INTO customers (customer_name,customer_tel) VALUES('黎明','13568898321')
SELECT LAST_INSERT_ID()#3
給出默認值,使用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, #給出默認值1
item_price decimal(8,2) NOT NULL,
PRIMARY KEY (order_num,order_item)
)ENGINE=INNODB
常見的引擎
- InnoDB 是一個可靠的事務處理引擎征椒,不支持文本搜索;
- MEMORY在功能上等同于MyISAM湃累,但由于數據存儲在內存而不是磁盤中勃救,所以速度很快,適合于臨時表脱茉;
- MyISAM是一個性能極高的引擎剪芥,支持全文搜索,但是不支持事務處理琴许;
刪除表
語法:DROP TABLE customers;
重新命名表名
語法:
RENAME TABLE customers TO customer;
更改表結果
新增列
ALTER TABLE customer
ADD createTime TIMESTAMP ;
DESCRIBE customer;
刪除列
ALTER TABLE customer
DROP createTime;
DESCRIBE customer;
添加外鍵
ALTER TABLE orderitems
ADD CONSTRAINT fk_01
FOREIGN KEY(order_num) REFERENCES orders (order_num)