SQL 句法
基础知识
- 数据库(database) – 表格(table) – 记录(record)& 列(column)
- 数据库操作通过SQL statements实现
- SQL 语句(statements)不区分大小写
- 某些数据库会要求语句最后添加分号(;),所以在所有语句最后添加分号才是标准写法
- 一些重要的SQL语句:
SELECT – extracts data from a database
UPDATE – updates data in a database
DELETE – deletes data from a database
INSERT INTO – inserts new data into a database
CREATE DATABASE – creates a new database
ALTER DATABASE – modifies a database
CREATE TABLE – creates a new table
ALTER TABLE – modifies a table
DROP TABLE – deletes a table
CREATE INDEX – creates an index (search key)
DROP INDEX – deletes an index
SQL语句
SELECT
用于从数据库中选择数据,结果储存在结果集合(result-set)中
SELECT column_name,column_name FROM table_name;
也可以用 * 表示全部列:
SELECT * FROM table_name;
SELECT DISTINCT
distinct是关键字(keyword),表示仅检索不同的值,必须放在列名前面,作用于其后的所有列
SELECT DISTINCT column_name,column_name FROM table_name;
WHERE
where是子句(clause)用于过滤结果,仅检索符合条件的记录
SELECT column_name,column_name FROM table_name WHERE column_name operator value;
- 对于字符串,SQL要求使用单引号( ’ ’ ),大多数数据库也支持双引号
如果是数字域,则不应该使用引号
SELECT * FROM Customers WHERE Country='Mexico'; SELECT * FROM Customers WHERE CustomerID=1;
- where中的操作符:
Operator | Description |
---|---|
= | Equal |
<> | Not equal. Note: In some versions of SQL this operator may be written as != |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
BETWEEN | Between an inclusive range |
LIKE | Search for a pattern |
IN | To specify multiple possible values for a column |
AND & OR
用于过滤多个条件
如:SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München');
ORDER BY
- 根据某一列或多列对结果集进行排序
默认升序排列,若要降序排列可以用DESC关键字,加在列名后面,只作用于最近的一列
SELECT column_name, column_name FROM table_name ORDER BY column_name ASC|DESC, column_name ASC|DESC;
INSERT INTO
- 往表格中插入新记录
可以指定列名(可仅指定某些列名,未指定的列名值为null)或不指定列名(value数需等于列数)
INSERT INTO table_name VALUES (value1,value2,value3,...); INSERT INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...);
UPDATE
- 更改已存在的记录
若没有where子句,则所有记录都会被更新
UPDATE table_name SET column1=value1,column2=value2,... WHERE some_column=some_value;
DELETE
- 删除记录
若没有where子句,则所有记录都会被删除(无法复原)
DELETE FROM table_name WHERE some_column=some_value; DELETE * FROM table_name;