DQL语言(数据查询语言 )
select语法:
SELECT [ALL | DISTINCT]
{* | table.* | [table.field1[as alias1][,table.field2[as alias2]][,…]]}
FROM table_name [as table_alias]
[left | right | inner join table_name2] – 联合查询
[WHERE …] – 指定结果需满足的条件
[GROUP BY …] – 指定结果按照哪几个字段来分组
[HAVING] – 过滤分组的记录必须满足的次要条件
[ORDER BY …] – 指定查询记录按一个或多个条件排序
[LIMIT {[offset,]row_count | row_countOFFSET offset}];-- 指定查询的记录从哪条至哪条
注意:[ ] 括号代表可选的 , { }括号代表必选得
- select语句: select (字段1,字段2,…) from 表名
测试:
--查询全部的学生,最好不要使用通配符*,效率低,不推荐
select `studentno`,`loginpwd`,`studentname`,`sex`,`gradeid`,`phone`,`address`,`borndate`,`email`,`identitycard` from `student`
--不推荐使用 select * from `student`
--查询指定字段
select `studentno`,`studentname` from `student`
- 别名 :As (既可以给字段起别名也可以给表起别名)
示例:
select `studentno` as 学号,`studentname` as 姓名 from `student` as s
一般来说,如果列名字或者字段名字看起来不是见名知意,我们可以通过起别名使用
- 函数 字符串拼接 :concat(a,b)
测试示例:
select concat('姓名:',`studentname`) as 新名字 from `student`
- 查询数据去重 distinct
作用:去除select查询出来的结果中重复的数据,只显示一条
测试示例:
--查询全部的考试成绩对应的id
select `studentno` from `result`
去重
select distinct `studentno` from `result`
- 查询一些数据库中的列
--查询数据库的版本(函数)
select version()
--计算结果(表达式)
select 100*5-1 as 计算结果
--查询自增的步长(变量)
select @@auto_increment_increment
where条件子句
作用:检索数据中符合条件的值,搜索条件由一个或多个表达式组成,结果为布尔值(true/false)
逻辑运算符
and (&&) :逻辑与,两个都为真结果为真
--查询成绩在95~100之间
select * from result where `studentresult`>=95 and `studentresult`<=100
select * from result where `studentresult`>=95 && `studentresult`<=100
--模糊查询(区间)
select * from result where `studentresult` between 95 and 100
or (||) :逻辑或,其中一个为真,则结果为真
--查询成绩等于70或者成绩等于85的数据
select * from result where `studentresult`=70 || `studentresult`=85
select * from result where `studentresult`=70 or `studentresult`=85
not (!) :逻辑非,真为假,假为真
--查询成绩不等于70的数据
select * from result where `studentresult` !=70
select * from result where not `studentresult` =70
select * from result where `studentresult` <> 70
注意:使用逻辑运算符尽量使用英文字母,可读性好
模糊查询:比较运算符
- between 值1 and 值2 :
--查询成绩在95到100分之间
select * from result where `studentresult` between 95 and 100
- in(具体的一个或多个值)
--查询学号在1000,1001,1002的数据
select * from student where studentno in(1000,1001,1002)
- is null :是否为空
--查询学生名字是否为null
select * from student where studentname is null
- is not null :不为空
--查询学生名字不为null
select * from student where studentname is not null
- like:模糊查询
--%代表0~任意个字符 _代表一个字符
select * from student where address like '%广东%'
select * from student where studentname like '赵_'