SQL复习笔记 - 查询
select * from sheetname # 查询所有字段
select column form sheetname #查询指定字段
select column1, column2, column3 from sheetname #查询多个字段用逗号隔开
select column1, column2, column3
from sheetname
where 查询条件 #查询指定记录
select id, name #带in的关键字查询
from sheetname
where id in (100,101)/where id not in (100,101)
order by name
#带(not)between and的字符查询
#带like的字符查询(可以和like放在一起使用的通配符有%和_
1,%匹配任意长度的字符,包括0
like 'b%'
查询结果 为blue blueberry等
2,通配符_ 一个_一个字符
like '_ _ _y'
查询结果 为 lily
#查询空值
select...is null
select...is not null
#null 不能和<>=号连用
#带and的多条件查询(同时满足)
select a,b,c from sheet1 where a=1 and b=2
#带or的多条件查询(满足任一)
#查询结果不重复
select distinct 字段名 from 表明
#对查询结果排序
select a from sheet1 order by a
#多列排序
select a from sheet1 order by a,b,c..
#指定排序升降 (默认升序,DESC实现降序)
select a,b from sheet1 order by a DESC
#分组查询 (group by)
1,创建分组
#group by常和集合函数一起用 比如max(),min (),count(),sum(),avg().
select id,count (*) as total from fruits group by id.
#group by可以和concat函数一起使用看到每个分组的每个字段
select id, group_concat(name) as names from fruits group by id.
2,使用having过滤
```sql
#语法
select name from consumer
where group by
having
order by
#例子
select id, group_concat(name) as names
from fruits
group by id having count(name)>1 order by name desc;
#WHERE 子句对被选择的列施加条件,而 HAVING 子句则对 GROUP BY 子句所 产生的组施加条件
3,在groupby中使用with roll up
#在查询分组之后新增一条记录,统计记录数量
select id, count(*)as total
from fruits
group by id with rollup;
4,多字段分组
select * from sheet1 group by id, name
5,group by和order by一起使用
select num, sum(quantityitem_price) as ordertotal
from ordertimes
group by num
having sum(quantityitem_price)>100;
```sql
select * from sheet1 limit 100
#limit限制查询结果数量
count() max() min() avg()
select sum(quantity) as item_total from orderitems where num=3005
select min(f_price) as min_price from fruits
#内连接 inner join
#外连接查询 left join、right join
#复合链接查询 在连接查询中,通过添加过滤条件限制查询结果
指一个查询语句嵌套在另一个查询语句内部的查询
#带any,some关键字的子查询
select num1 from table1 where num1> any (select num2 from table2)
#带all关键字的子查询
#带exists关键字的子查询(exist后面的参数是任意一个子查询)
select * from fruits where exists
(select name from suppliers where id=1)
#带in关键字的子查询
#带比较运算符的子查询
利用union关键字,给出多条select语句,并将他们的结果组合成单个结果集
select id,name,price
from fruits
where price<9
UNION select id,name,price
from fruits
where
id in (1,2) #Agroup=查询价格小于9的水果,Bgroup =id在1,2之间的水果,A+B用union连接
表明 as 表别名
select c.c_id,o.o_id
from customers as c left outer join orders as o
on c.c_id=o.o_id
select name,city+road+address+‘,邮编’+邮编 as 地址 from consumer
#mysql 中字符拼接需要使用concat函数
select name,concat(city,road,address,'邮编‘,邮编)as 地址
### 7,使用正则表达式查询
```c
^b 匹配以字母b开头的字符串 boook
bt$ 匹配以bt结尾的字符串 aaabt
b.t 匹配任何b和t之间有一个字符的字符串 bit
b*t匹配字符串n前面有任意个字符b的字符串 bavdlt
bt+ 匹配以b开头后面紧跟至少有一个t的字符串 bttes
bt 匹配包含bt的字符串 wosbtse
[bt]匹配包含b或者t的字符串 boo
[^bt] 匹配任何不包含b或t的字符串 rieo
b{2} 匹配2个或者更多个b bbbo
b{2,4}匹配最少2个最多4个b的字符串 bbbo
select * from table1 where name REGEXP '^b'
select * from table1 where name REGEXP 't$'
note: sql不区分大小写,*为通配符,DESC查看表结构