标签:style 脚本 add move explain comment engine example default
之前 manipulate 表里的数据,现在则是 manipulate 表本身。
非常工整的 。 。模范脚本:
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;
Simply specify the column names as a comma delimited list, as seen in this example:
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;
CREATE TABLE `manga` ( `manga_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT ‘漫画id‘, `manga_name` varchar(40) NOT NULL COMMENT ‘漫画名字‘, `manga_discription` varchar(120) DEFAULT NULL COMMENT ‘漫画描述‘, `manga_status` tinyint(4) NOT NULL DEFAULT ‘0‘ COMMENT ‘漫画描述‘, PRIMARY KEY (`manga_id`) ) ENGINE=InnoDB AUTO_INCREMENT=1012 DEFAULT CHARSET=utf8 COMMENT=‘漫画表‘
每个表只允许有一个自增列,并且它必须被索引(例如,把它设置为主键)
必须是自增的!自定义插入的不算!
mysql> INSERT INTO manga -> (manga_name) VALUES (‘what‘); Query OK, 1 row affected (0.00 sec) mysql> SELECT last_insert_id(); +------------------+ | last_insert_id() | +------------------+ | 1012 | +------------------+ 1 row in set (0.00 sec)
Many database developers use DEFAULT values instead of NULL columns, especially in columns that will be used in calculations or data groupings.
There is one big downside to mixing engine types. Foreign keys (used to enforce referential integrity, as explained in Chapter 1, "Understanding SQL") cannot span engines. That is, a table using one engine cannot have a foreign key referring to a table that uses another engine.
ALTER TABLE vendors ADD vend_phone CHAR(20);
ALTER TABLE Vendors DROP COLUMN vend_phone;
修改表这一操作经常被用来定义外键:
ALTER TABLE orderitems ADD CONSTRAINT fk_orderitems_orders FOREIGN KEY (order_num) REFERENCES orders (order_num); ALTER TABLE orderitems ADD CONSTRAINT fk_orderitems_products FOREIGN KEY (prod_id) REFERENCES products (prod_id); ALTER TABLE orders ADD CONSTRAINT fk_orders_customers FOREIGN KEY (cust_id) REFERENCES customers (cust_id); ALTER TABLE products ADD CONSTRAINT fk_products_vendors FOREIGN KEY (vend_id) REFERENCES vendors (vend_id);
语法:ALTER TABLE table_name ADD CONSTRAINT fk_id FOREIGN KEY (外键字段名) REFERENCES 外表表明(外表中对应的主键字段名);
FK_ID 是外键的名称。更多外键相关的内容请参考 外键约束
Complex table structure changes usually require a manual move process involving these steps:
DROP TABLE customers2;
RENAME TABLE backup_customers TO customers, backup_vendors TO vendors, backup_products TO products;
MySQL Crash Course #13# Chapter 21. Creating and Manipulating Tables
标签:style 脚本 add move explain comment engine example default
原文地址:https://www.cnblogs.com/xkxf/p/8904004.html