以下是经常用到的SQL创建语句(适用于MySQL):
创建数据库:
CREATE DATABASE IF NOT EXISTS database_name DEFAULT CHARACTER SET utf-8
创建表:
CREATE TABLE IF NOT EXISTS table_name (<col_name1> <datatype> <constraints>, <col_name2> <datatype> <constraints>, <col_name3> <datatype> <constraints>, ...);
例子:
CREATE TABLE IF NOT EXISTS Student (st_no SMALLINT(5) PRIMARY KEY AUTO_INCREMENT, st_name VARCHAR(50) NOT NULL, birth DATETIME NOT NULL DEFAULT DATETIME('now','localtime'));
创建关系:
CREATE TABLE IF NOT EXISTS Student (st_no SMALLINT(5) PRIMARY KEY AUTO_INCREMENT, st_name VARCHAR(50) NOT NULL, class_no SMALLINT(5) NOT NULL, FOREIGN KEY fk_student_class (class_no) REFENCES class (class_no) ON UPDATE CASCADE ON DELETE NO ACTION );
复制表:
CREATE TABLE table_name2 AS SELECT * FROM table_name1
创建视图:
CREATE VIEW view_name AS SELECT ...
删除数据库:
DROP DATABASE IF EXISTS database_name;
删除表:
DROP TABLE IF EXISTS table_name;
删除视图:
DROP VIEW view_name;
创建索引:
CREATE INDEX index_name ON table_name (col_name);
查看索引:
SHOW INDEXES IN table_name;
强制索引:
SELECT ... FROM ... INDEXED BY index_name