指定字段查询

查询语句

  1. /*查询全部信息*/
  2. SELECT * FROM student;
  3. /*查询指定字段 别名(AS) 可以给字段取别名 也可以给表取别名*/
  4. SELECT `StudentNo` AS 学号,`StudentName` AS 姓名 FROM `student`;
  5. /*函数 concat(a,b) 拼接字符串*/
  6. SELECT CONCAT('姓名:',`StudentName`) AS 重命名 FROM `student`;

去重(distinct)

去除select语句查询出来的重复的数据 只保留一条
关键字 distinct

  1. SELECT DISTINCT `StudentNo` FROM `result`;

列(表达式)

  1. /*查询版本号*/
  2. SELECT VERSION() --(函数)
  3. /*用于计算*/
  4. SELECT 3*100-1; --(表达式)
  5. /*查询自增的步长*/
  6. SELECT @@auto_increment_increment --(变量)
  7. /*学生成绩+1*/
  8. SELECT `StudentNo`,`StudentResult`+1 AS 加分后成绩 FROM `result`;

数据库中的表达式:文本值,列,null,函数,计算表达式,系统变量….
Select 表达式 from 表名

where条件子句

作用:检索数据中符合条件的值

逻辑运算符

运算符 语法 描述
and && A and b a && b 逻辑与
or || A or b a || b 逻辑或
not ! Not a ! a 逻辑非
  1. SELECT `StudentNo`,`StudentResult` FROM `result`
  2. WHERE `StudentResult`>=80 AND `StudentResult`<=90;
  3. SELECT `StudentNo`,`StudentResult` FROM `result`
  4. WHERE `StudentResult` BETWEEN 80 AND 90;
  5. SELECT `StudentNo`,`StudentResult` FROM `result`
  6. WHERE `StudentNo`!=111;
  7. SELECT `StudentNo`,`StudentResult` FROM `result`
  8. WHERE `StudentNo`<>112;

比较运算符

运算符 语法 描述
Is null A is null 如果操作符为null 返回真
Is not null A is not null 如果操作符不为null 返回真
Between Between a and b 如果在a和b之间 返回真
Like A like b 如果a能匹配到b 返回真
In A in (a,b,c) 如果a在()中 返回真

模糊查询

  1. --==============LIKE==================
  2. --结合 %(0到任意个字符) _(代表一个字符)
  3. --查询姓张的同学
  4. SELECT `StudentNo`,`StudentName` FROM `student`
  5. WHERE `StudentName` LIKE '张%';
  6. --查询姓张,后面只有一个字的
  7. SELECT `StudentNo`,`StudentName` FROM `student`
  8. WHERE `StudentName` LIKE '张_';
  9. --查询姓张,后面只有两个字的
  10. SELECT `StudentNo`,`StudentName` FROM `student`
  11. WHERE `StudentName` LIKE '张__';
  12. --查询名字里带三的同学
  13. SELECT `StudentNo`,`StudentName` FROM `student`
  14. WHERE `StudentName` LIKE '%三%';
  15. /*==================in================ */
  16. --查询 111112113
  17. SELECT `StudentNo`,`StudentName` FROM `student`
  18. WHERE `StudentNo` IN (111,112,113);
  19. /************null,not null***********/
  20. SELECT `StudentNo`,`StudentName`,`Address`FROM `student`
  21. WHERE `Address`='' OR `Address` IS NULL;
  22. SELECT `StudentNo`,`StudentName`,`Address`FROM `student`
  23. WHERE `Address` IS NOT NULL;