SQL是一組語法的獨特規則和準則。 本教學通過列出所有基本SQL語法,為讀者提供SQL快速入門。
所有SQL語句都以:SELECT,INSERT,UPDATE,DELETE,ALTER,DROP,CREATE,USE
,SHOW
等任何關鍵字開頭,所有語句都以分號(;
)結尾。
這裡要注意的最重要的一點是SQL不區分大小寫,所以語句:SELECT
和select
在SQL語句中具有相同的含義。 然而,MySQL在表名稱是區分大小寫的。 因此,如果使用MySQL,那麼表命名時需要注意。
注意:本教學中給出的所有範例僅使用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;