SELECT查询

查询表中所有字段的数据

  1. SELECT * FROM 表名;

换行形式显示记录

  1. SELECT * FROM 表名 \G;

查询表中部分字段的数据

  1. SELECT column1, column2, ... FROM table

查询表中部分列的数据,并且在查询结果中加入表中不包含的数据

  1. SELECT id, title, '美国' as country FROM movies

WHERE条件查询

  1. 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 插入记录

插入包含所有列值的语句

  1. INSERT INTO mytable
  2. VALUES (value_or_expr, another_value_or_expr, …),
  3. (value_or_expr_2, another_value_or_expr_2, …),
  4. …;

插入包含特定列的语句

  1. INSERT INTO mytable
  2. (column, another_column, …)
  3. VALUES (value_or_expr, another_value_or_expr, …),
  4. (value_or_expr_2, another_value_or_expr_2, …),
  5. …;

可以将数学和字符串表达式与您要插入的值一起使用。
这有助于确保插入的所有数据都以某种方式格式化。

  1. INSERT INTO boxoffice (movie_id, rating, sales_in_millions) VALUES (1, 9.9, 283742034 / 1000000);

UPDATE 更新记录

使用值更新语句

  1. UPDATE mytable SET column = value_or_expr, other_column = another_value_or_expr, WHERE condition;

注意:
SET段有多个列需要修改时,需要用 , 分隔

DELETE 删除记录

删除记录,数据可以找回

  1. DELETE FROM mytable WHERE condition;

删除表并重建包含原字段新表,数据不能找回

  1. TRUNCATE TABLE 表名;