SQL documentation

安装教程

法则1:col

法则2:select

select col,col,col,* 找什么
FROM table 从哪找?
WHERE col 条件 条件是啥?

条件:数字(where)

当查找条件col是数字

select * from table where col = 1;

Operator Condition SQL Example 解释
=, !=, <, <=, >, >= Standard numerical operators col != 4 等于 大于 小于
BETWEEN … AND … Number is within range of two values (inclusive)Numb col_name BETWEEN 1.5 AND 10.5 在X和X之间
NOT BETWEEN … AND … Number is not within range of two values (inclusive) col_name NOT BETWEEN 1 AND10 不在X和X之间
IN (…) Number exists in a list col_name IN (2, 4, 6) 在X集合
NOT IN (…) Number does not exist in a list col_name NOT IN (1, 3, 5) 不在X集合

条件: 文本(where)

Operator Condition Example 解释
= Case sensitive exact string comparison (notice the single equals) col_name = "abc" 等于
!= or <> Case sensitive exact string inequality comparison col_name != "abcd" 不等于
LIKE Case insensitive exact string comparison col_name LIKE "ABC" 等于
NOT LIKE Case insensitive exact string inequality comparison col_name NOT LIKE "ABCD" 不等于
% Used anywhere in a string to match a sequence of zero or more characters (only with LIKE or NOT LIKE) col_name LIKE "%AT%" (matches "AT", "ATTIC", "CAT" or even "BATS") 模糊匹配
_ Used anywhere in a string to match a single character (only with LIKE or NOT LIKE) col_name LIKE "AN_" (matches "AND", but not "AN") 模糊匹配单字符
IN (…) String exists in a list col_name IN ("A", "B", "C") 在集合
NOT IN (…) String does not exist in a list col_name NOT IN ("D", "E", "F") 不在集合

排序(rows)

需要对结果rows排序和筛选部分rows

select * from table where col > 1 order by col asc limit 2 offset 2

Operator Condition Example 解释
ORDER BY . ORDER BY col ASC/DESC 按col排序
ASC . ORDER BY col ASC/DESC 升序
DESC . ORDER BY col ASC/DESC 降序
LIMIT OFFSET . LIMIT num_limit OFFSET num_offset 从offset取limit
ORDER BY . ORDER BY col1 ASC, col2 DESC 多列排序

合并(INNER/LEFT/RIGHT/FULL JOIN)

SELECT column, another_column, …
FROM mytable
INNER/LEFT/RIGHT/FULL JOIN another_table 
    ON mytable.id = another_table.matching_id
WHERE condition(s)
ORDER BY column, … ASC/DESC
LIMIT num_limit OFFSET num_offset;

NULL(IS/IS NOT NULL)

SELECT column, another_column, …
FROM mytable
WHERE column IS/IS NOT NULL
AND/OR another_condition
AND/OR …;

表达式

SELECT particle_speed / 2.0 AS half_particle_speed
FROM physics_data
WHERE ABS(particle_position) * 10.0 > 500;
SELECT col_expression AS expr_description, …
FROM mytable;
--Example query with both column and table name aliases
SELECT column AS better_column_name, …
FROM a_long_widgets_table_name AS mywidgets
INNER JOIN widget_sales
  ON mywidgets.id = widget_sales.widget_id;

聚合函数

Function Description
COUNT(*****), COUNT(column) A common function used to counts the number of rows in the group if no column name is specified. Otherwise, count the number of rows in the group with non-NULL values in the specified column.
MIN(column) Finds the smallest numerical value in the specified column for all rows in the group.
MAX(column) Finds the largest numerical value in the specified column for all rows in the group.
AVG(column) Finds the average numerical value in the specified column for all rows in the group.
SUM(column) Finds the sum of all numerical values in the specified column for the rows in the group.

Docs: MySQL, Postgres, SQLite, Microsoft SQL Server

GROUP BY

--Select query with aggregate functions over groups
SELECT AGG_FUNC(column_or_expression) AS aggregate_description, …
FROM mytable
WHERE constraint_expression
GROUP BY column;

if the GROUP BY clause is executed after the WHEREclause, SQL allows us to do this by adding an additional HAVING clause which is used specifically with the GROUP BY clause to allow us to filter grouped rows from the result set.

--Select query with HAVING constraint
SELECT group_by_column, AGG_FUNC(column_expression) AS aggregate_result_alias, …
FROM mytable
WHERE condition
GROUP BY column
HAVING group_condition;

插入行

--Insert statement with specific columns
INSERT INTO mytable
(column, another_column, …)
VALUES (value_or_expr, another_value_or_expr, …),
      (value_or_expr_2, another_value_or_expr_2, …),
      …;

修改行

--Update statement with values
UPDATE mytable
SET column = value_or_expr, 
    other_column = another_value_or_expr, 
    …
WHERE condition;

删除行

--Delete statement with condition
DELETE FROM mytable
WHERE condition;

创建表格

--Create table statement w/ optional table constraint and default value
CREATE TABLE IF NOT EXISTS mytable (
    column DataType TableConstraint DEFAULT default_value,
    another_column DataType TableConstraint DEFAULT default_value,
    …
);

Table data types

Data type Description
INTEGER, BOOLEAN The integer datatypes can store whole integer values like the count of a number or an age. In some implementations, the boolean value is just represented as an integer value of just 0 or 1.
FLOAT, DOUBLE, REAL The floating point datatypes can store more precise numerical data like measurements or fractional values. Different types can be used depending on the floating point precision required for that value.
CHARACTER(num_chars), VARCHAR(num_chars), TEXT The text based datatypes can store strings and text in all sorts of locales. The distinction between the various types generally amount to underlaying efficiency of the database when working with these columns.Both the CHARACTER and VARCHAR (variable character) types are specified with the max number of characters that they can store (longer values may be truncated), so can be more efficient to store and query with big tables.
DATE, DATETIME SQL can also store date and time stamps to keep track of time series and event data. They can be tricky to work with especially when manipulating data across timezones.
BLOB Finally, SQL can store binary data in blobs right in the database. These values are often opaque to the database, so you usually have to store them with the right metadata to requery them.

Docs: MySQL, Postgres, SQLite, Microsoft SQL Server

Table constraints

Constraint Description
PRIMARY KEY This means that the values in this column are unique, and each value can be used to identify a single row in this table.
AUTOINCREMENT For integer values, this means that the value is automatically filled in and incremented with each row insertion. Not supported in all databases.
UNIQUE This means that the values in this column have to be unique, so you can't insert another row with the same value in this column as another row in the table. Differs from the PRIMARY KEY in that it doesn't have to be a key for a row in the table.
NOT NULL This means that the inserted value can not be NULL.
CHECK (expression) This is allows you to run a more complex expression to test whether the values inserted are value. For example, you can check that values are positive, or greater than a specific size, or start with a certain prefix, etc.
FOREIGN KEY This is a consistency check which ensures that each value in this column corresponds to another value in a column in another table. For example, if there are two tables, one listing all Employees by ID, and another listing their payroll information, the FOREIGN KEY can ensure that every row in the payroll table corresponds to a valid employee in the master Employee list.

Example

--Movies table schema
CREATE TABLE movies (
    id INTEGER PRIMARY KEY,
    title TEXT,
    director TEXT,
    year INTEGER, 
    length_minutes INTEGER
);

修改表格

添加列

--Altering table to add new column(s)
ALTER TABLE mytable
ADD column DataType OptionalTableConstraint 
    DEFAULT default_value;

删除列

--Altering table to remove column(s)
ALTER TABLE mytable
DROP column_to_be_deleted;

重命名表格

--Altering table name
ALTER TABLE mytable
RENAME TO new_table_name;

其他

Documentation: MySQL, Postgres, SQLite, Microsoft SQL Server.

删除表格

--Drop table statement
DROP TABLE IF EXISTS mytable;

注:In addition, if you have another table that is dependent on columns in table you are removing (for example, with a FOREIGN KEY dependency) then you will have to either update all dependent tables first to remove the dependent rows or to remove those tables entirely.

你可能感兴趣的:(SQL documentation)