前言
数据库是必备知识,更是面试时必问,要会最基本的增、删、改、查,推荐一个刷SQL题的网站http://xuesql.cn/lesson/filtering_sorting_query_results
写此文是记录一下,SQL的知识点,以便今后查漏补缺
数据库查询:(Select)
基本查询语句:
Select (列名)from (表名)
SELECT * FROM mytable(表名)
下面的具体语法规则,可以用来筛选数字属性列(包括 整数,浮点数) :
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个字符 | 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") |
ps:LIKE与“=”的区别在与,LIKE用于模糊匹配,例:
找到所有电影名为 "WALL-"
开头的电影 select * from movies where like"WALL-%"
查询结果Filtering过滤 和 sorting排序:
关键词:去重(去除重复的数据)(distinct) 句式:SELECT DISTINCT column, another_column, … FROM mytable WHERE condition(s)
排序(排列顺序) (order by) 句式:SELECT column, another_column, … FROM mytable WHERE condition(s) ORDER BY column ASC/DESC;
选取结果: (limit返回多少行结果,offset从哪开始剪)SELECT column, another_column, … FROM mytable WHERE condition(s) ORDER BY column ASC/DESC LIMIT num_limit OFFSET num_offset(例:按电影名字母序升序
排列,列出前5部电影,select * from movies order by title limit 5 offset 0)