一、单表查询
USE sql_store;--use关键字选中数据库,不分大小写
SELECT *--*表示返回所有的列
FROM customers--明确要查询的表
WHERE customer_id=1
ORDER BY fist_name,last_name
----------------------
--SELECT选择数据
SELECT fist_name,last_name,points,points+10,--可做+—*/%操作
points*10+100,--基于数学运算符次序
(points+10)*100 AS discount_factor--"discount factor" /'discount factor' AS关键字命名
FROM CUSTOMERS
-----------------------
--WHERE筛选数据
SELECT *
FROM CUSTOMERS
WHERE points>30
WHERE stste='va'
WHERE state!='va'--等同于WHERE state<>'va'
WHERE birth_date>'1990_01_01'
--注:一个选择语句只能有一句WHERE语句
----------------------
--AND,OR,NOT运算符
SELECT *
FROM CUSTOMERS
WHERE birth_date>'1990_01_01'AND points>1000
WHERE birth_date>'1990_01_01'OR points>1000
WHERE birth_date>'1990_01_01'OR points>1000 AND state='VA'
--AND运算符总是被优先评估
WHERE NOT (birth_date>'1990_01_01' OR points>1000)
--等价于WHERE birth_date<='1990_01_01'AND points<=1000
--------------------------------
--IN运算符
SELECT *
FROM customers
WHERE state IN ('VA','FL','GA')
--------------------------------------
--BETWEEN运算符
SELECT *
FROM customers
-- WHERE points>=1000 AND points<=3000 用between改写
WHERE points BETWEEN 1000 AND 3000
----------------------------------------------
--LIKE运算符,检索遵循特定字符串模式的字
SELECT *
FROM customers
WHERE last_name LIKE 'b%'--所有姓氏以"B"打头的顾客
WHERE last_name LIKE '%b%'--寻找姓氏中有"b"的顾客
WHERE last_name LIKE '%y'--搜寻以y结尾的顾客
WHERE last_name LIKE '_y'--获取姓氏正好为两个字符串长度且第二个字符串为y的顾客
--使用%代表任意字符数,使用"_"代表一个单字符
----------------------------------------
--REGEXP运算符,正则表达式
SELECT*
FROM customers
WHERE last_name LIKE "%field%"正则表达式改写如下
WHERE last_name REGEXP "field"
-- ^表示字符串的开头
--$表示字符串的结尾
--|表示“或”条件
-- WHERE last_name REGEXP "^field|mac$|rose"
--确保字母e前有g或者i两者之一,表达式如下
WHERE last_name REGEXP '[gi]e'
WHERE last_name REGEXP 'e[fmg]'--确保字母e后有fmg三者之一
WHERE last_name REGEXP '[a-h]e'--在e前面可以有从a到h的任意字母
-----------------------------------------
--IS NULL 运算符
SELECT *
FROM customers
WHERE phone IS NULL--查询没有电话号码的顾客
-----------------------------------------------
--ORDER BY 排序子句
SELECT *
FROM customers
ORDER BY state DESC,first_name --根据state和first_name 排序,默认升序,加DESC结尾表示降序
---------------------------------------
-- LIMIT子句
SELECT *
FROM customers
LIMIT 3--返回前三位顾客
--假设每页只展示3位顾客
--page 1:1-3
--page 2:4-6
--page 3:7-9
--查询第三页数据
SELECT *
FROM customers
LIMIT 6,3--跳过前6条语句,选择3条语句,6称为偏移量
--语句顺序
--SELECT *
--FROM
-- WHERE
--ORDER BY
--LIMIT