查询语句:select
语法:
-
查询全部学生:SELECT * FROM 表名
-
查询指定字段:
SELECT 字段1,字段2,… FROM 表名
-
起别名:使用
AS
(表和字段都可使用):
字段名 AS 别名 或者 表名 AS 别名
-
函数:
CONCAT(a, b)
-
去重:
distinct
作用:去除select查询出来的结果重复的数据,只保留一条
-
数据库的列(表达式)其他用法
演示
-- 查询全部学生: SELECT * FROM 表名
SELECT * FROM `student`
-- 查询指定字段:SELECT 字段1,字段2,... FROM 表名
SELECT `studentno`,`studentname` FROM `student`
-- 起别名:使用 AS(表和字段都可使用):字段名 AS 别名、表名 AS 别名
SELECT `studentno` AS 学号,`studentname` AS 学生姓名 FROM `student` AS s
-- 函数:CONCAT(a, b)
SELECT CONCAT('姓名:',studentname) AS 新名字 FROM `student`
-- 去重:distinct
SELECT `studentno` FROM `result` -- 查询哪些学生参加了考试
SELECT DISTINCT `studentno` FROM `result` -- 去掉重复数据
-- 数据库的列(表达式)其他用法
SELECT VERSION() -- 查询系统版本号(函数)
SELECT 66*3-1 AS 计算结果 -- 用来计算(表达式)
SELECT @@auto_increment_increment -- 查询自增的步长(变量)
-- 增加所有值
SELECT `studentno`,`studentresult` FROM result -- 原本数据
SELECT `studentno`,`studentresult` + 1 AS 提分后 FROM result -- studentresult值全部加1
where条件子句
作用:检索数据中
符合条件的值
逻辑运算符
运算符 | 语法 | 描述 |
---|---|---|
and && | x and y x && y | 逻辑与:两个都为真,结果为真 |
or || | x or y x || y | 逻辑或:其中一个为真,结果为真 |
not != | not x !x | 逻辑非:真为假,假为真 |
演示
-- 查询成绩为90~100分之间
SELECT `studentno`,`studentresult` FROM `result`
WHERE `studentresult`>=90 AND `studentresult`<=100
-- 使用模糊查询:between and
SELECT `studentno`,`studentresult` FROM `result`
WHERE `studentresult` BETWEEN 90 AND 100
-- 查询除了1000号之外的成绩
SELECT `studentno`,`studentresult` FROM `result`
WHERE `studentno`!=1000
-- 还可以写成
SELECT `studentno`,`studentresult` FROM `result`
WHERE NOT `studentno`=1000
模糊查询:比较运算符
运算符 | 语法 | 描述 |
---|---|---|
IS NULL | a is null | 如果操作符为null ,结果为真 |
IS NOT NULL | a is not null | 如果操作符不为null,结果为真 |
between and | a between b and c | 若a在b和c之间,则结果为真 |
like |
a like b | 如果a匹配b,则结果为真 |
in |
a in(a1,a2,…) | 若a在a1,或者a2…其中的某一个值中,结果为真 |
演示
-- like %:多个字符 _:一个字符
-- 查询姓张的全部学生
SELECT `studentno`,`studentname` FROM `student`
WHERE `studentname` LIKE '张%'
-- 查询两个字后带伟的学生
SELECT `studentno`,`studentname` FROM `student`
WHERE `studentname` LIKE '_伟'
-- in(具体的一个或多个值)
-- 查询1000,1002号学生
SELECT `studentno`,`studentname` FROM `student`
WHERE `studentno` IN (1000,1002)
-- null not null
-- 查询地址为空的学生,有两种代表空所以加or
SELECT `studentno`,`studentname` FROM `student`
WHERE address = '' OR address IS NULL
-- 查询生日不为空的
SELECT `studentno`,`studentname` FROM `student`
WHERE `borndate` IS NOT NULL
-- 查询生日为空的
SELECT `studentno`,`studentname` FROM `student`
WHERE `borndate` IS NULL
select完整语法
select[all | distinct]
{* | table.* | [table.field1[as alias1][,table.field2[as alias2]][,...]]}
from table_name [as table_alias]
[inner | left | right join table_name2] --联合查询
[where ...] --指定结果需满足的条件
[group by ...] -- 指定结果按照哪几个字段来分组
[having] -- 过滤分组的记录必须满足的次要条件
[order by ...] -- 指定查询记录按一个或多个条件排序
[limit {[offset,]row_count | row_countoffset offset}]; -- 指定查询的记录从哪条至哪条
版权声明:本文为weixin_46649583原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。