MySQL常用命令(十)-建表语句

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来判定表是否存在,如果存在则不进行创建;
每个表只能有一个AUTO_INCREMENT;

SELECT LAST_INSERT_ID()

查询最后插入的id值,适用于查询自增主键值;
但是对于批量插入和单个插入的值返回会有区别,具体见下面的例子:

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)

你可能感兴趣的:(MySQL常用命令(十)-建表语句)