📜  SQL-语法

📅  最后修改于: 2020-12-29 04:30:07             🧑  作者: Mango


SQL之后是一组称为语法的独特规则和准则。本教程通过列出所有基本的SQL语法为您快速入门SQL。

所有SQL语句均以SELECT,INSERT,UPDATE,DELETE,ALTER,DROP,CREATE,USE,SHOW等任何关键字开头,并且所有语句均以分号(;)结尾。

这里要注意的最重要一点是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

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语句(重命名)

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;