SELECT查询
查询表中所有字段的数据
SELECT * FROM 表名;
换行形式显示记录
SELECT * FROM 表名 \G;
查询表中部分字段的数据
SELECT column1, column2, ... FROM table
查询表中部分列的数据,并且在查询结果中加入表中不包含的数据
SELECT id, title, '美国' as country FROM movies
WHERE条件查询
SELECT column1, column2, ... FROM table WHERE condition1 AND/OR condition2 ...
对数字类型(证书、浮点数)数据进行筛选的条件:
Operator(操作符) | Condition(解释) | SQL Example(例子) |
---|---|---|
= | ||
=, !=, < <=, >, >= | Standard numerical operators 基础的 大于,等于等比较 | col_name != 4 |
BETWEEN … AND … | Number is within range of two values (inclusive) 在两个数之间 | col_name BETWEEN 1.5 AND 10.5 |
NOT BETWEEN … AND … | Number is not within range of two values (inclusive) 不在两个数之间 | col_name NOT BETWEEN 1 AND 10 |
IN (…) | Number exists in a list 在一个列表 | col_name IN (2, 4, 6) |
NOT IN (…) | Number does not exist in a list 不在一个列表 | col_name NOT IN (1, 3, 5) |
对字符串类型数据进行筛选:
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) 通配符,代表匹配0个以上的字符 | col_name LIKE “%AT%”(matches “AT”, “ATTIC”, “CAT” or even “BATS”) “%AT%” 代表AT 前后可以有任意字符 |
_ | Used anywhere in a string to match a single character (only with LIKE or NOT LIKE) 和% 相似,代表1个字符 | colname 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”) |
INSERT INTO 插入记录
插入包含所有列值的语句
INSERT INTO mytable
VALUES (value_or_expr, another_value_or_expr, …),
(value_or_expr_2, another_value_or_expr_2, …),
…;
插入包含特定列的语句
INSERT INTO mytable
(column, another_column, …)
VALUES (value_or_expr, another_value_or_expr, …),
(value_or_expr_2, another_value_or_expr_2, …),
…;
可以将数学和字符串表达式与您要插入的值一起使用。
这有助于确保插入的所有数据都以某种方式格式化。
INSERT INTO boxoffice (movie_id, rating, sales_in_millions) VALUES (1, 9.9, 283742034 / 1000000);
UPDATE 更新记录
使用值更新语句
UPDATE mytable SET column = value_or_expr, other_column = another_value_or_expr, … WHERE condition;
DELETE 删除记录
删除记录,数据可以找回
DELETE FROM mytable WHERE condition;
删除表并重建包含原字段新表,数据不能找回
TRUNCATE TABLE 表名;