语法格式
-- 基本的查询语法
SELECT 字段1,字段2,... FROM 表名
-- 查询所有的字段
SELECT * FROM 表名
-- 带条件的查询
SELECT * FROM 表名 [WHERE 条件] [ORDER BY 排序字段[, 排序字段]] LIMIT [开始位置,]长度
一。基本查询
格式: select 字段名1, 字段名2,.... from 表名
select name,nickname from heroes
二带where子句的查询:where 可以使用条件来筛选查询出的结果
select * from heroes where age>=20 and age<=30
-- select * from heroes where age between 20 and 30
三模糊查询
通配符:
%: 代表任意长度(包括0)的任意字符
_: 代表1位长度的任意字符
like: 在执行模糊查询时,必须使用like来作为匹配条件
-- 查询名字中带有 “斯” 字的英雄
-- select * from heroes where name like '%斯%'
-- 查询名字中带有斯字的英雄,但是要求斯在最后
-- select * from heroes where name like '%斯'
-- 查询名字中带有斯,但是要求斯是第二个字
select * from heroes where name like '_斯%'
四查询结果排序
order by 可以对查询结果按某个字段进行升序或者降序排列
升序 asc (默认值)
降序 desc
可进行排序的字段通常是 整型 英文字符串型 日期型 (中文字符串也行,但一般不用)
- -查询年龄大于50岁的英雄,并按年龄降序排序
select * from heroes where age>50 order by age desc
五。限制查询结果
limit 用来限制查询结果的起始点和长度
查询年龄最大的3个女英雄
select * from heroes where sex='女' order by age desc limit 3