SQL是一组语法的独特规则和准则。 本教程通过列出所有基本SQL语法,为读者提供SQL快速入门。
所有SQL语句都以:SELECT,INSERT,UPDATE,DELETE,ALTER,DROP,CREATE,USE
,SHOW
等任何关键字开头,所有语句都以分号(;
)结尾。
- SQL不区分大小写。通常SQL关键字以大写形式编写。
- SQL语句依赖于文本行,可以在一个或多个文本行上放置一个SQL语句。
- 使用SQL语句可以在数据库中执行大多数操作。
- SQL依赖于关系代数和元组关系演算。
这里要注意的最重要的一点是SQL不区分大小写,所以语句:SELECT
和select
在SQL语句中具有相同的含义。 然而,MySQL在表名称是区分大小写的。 因此,如果使用MySQL,那么表命名时需要注意。
SQL常用语法
注意:本教程中给出的所有示例仅使用MySQL服务器进行了测试。
SQL SELECT语句
SELECT column1, column2....columnN
FROM table_name;
SQL DISTINCT子句
SELECT DISTINCT column1, column2....columnN
FROM table_name;
SQL WHERE子句
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION;
SQL AND/OR子句
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION-1 {AND|OR} CONDITION-2;
SQL IN子句
SELECT column1, column2....columnN
FROM table_name
WHERE column_name IN (val-1, val-2,...val-N);
SQL BETWEEN子句
SELECT column1, column2....columnN
FROM table_name
WHERE column_name BETWEEN val-1 AND val-2;
SQL Like子句
SELECT column1, column2....columnN
FROM table_name
WHERE column_name LIKE { PATTERN };
SQL ORDER BY子句
SELECT column1, column2....columnN
FROM table_name
WHERE CONDITION
ORDER BY column_name {ASC|DESC};
SQL GROUP BY子句
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name;
SQL COUNT子句
SELECT COUNT(column_name)
FROM table_name
WHERE CONDITION;
SQL HAVING子句
SELECT SUM(column_name)
FROM table_name
WHERE CONDITION
GROUP BY column_name
HAVING (arithematic function condition);
SQL CREATE TABLE语句
CREATE TABLE table_name(
column1 datatype,
column2 datatype,
column3 datatype,
.....
columnN datatype,
PRIMARY KEY( one or more columns )
);
SQL DROP TABLE语句
DROP TABLE table_name;
SQL CREATE INDEX语句
CREATE UNIQUE INDEX index_name
ON table_name ( column1, column2,...columnN);
SQL DROP INDEX语句
ALTER TABLE table_name
DROP INDEX index_name;
SQL DESC语句
DESC table_name;
SQL TRUNCATE TABLE语句
TRUNCATE TABLE table_name;
SQL ALTER TABLE语句
ALTER TABLE table_name {ADD|DROP|MODIFY} column_name {data_ype};
SQL ALTER TABLE(rename)语句
ALTER TABLE table_name RENAME TO new_table_name;
SQL INSERT INTO语句
INSERT INTO table_name( column1, column2....columnN)
VALUES ( value1, value2....valueN);
SQL UPDATE语句
UPDATE table_name
SET column1 = value1, column2 = value2....columnN=valueN
[ WHERE CONDITION ];
SQL DELETE语句
DELETE FROM table_name
WHERE {CONDITION};
SQL CREATE DATABASE语句
CREATE DATABASE database_name;
SQL DROP DATABASE语句
DROP DATABASE database_name;
SQL USE语句
USE database_name;
SQL COMMIT语句
COMMIT;
SQL ROLLBACK语句
ROLLBACK;