MySQL笔记-select单表查询

来源:互联网 发布:无法淘宝建立私密连接 编辑:程序博客网 时间:2024/06/04 19:52

一、select 基本语法

语法:

select column1 [,column2,……] from 数据表 [where condition];


二、select语句更多功能

1、算术运算符

使用select查询时,可在select语句的选择列部分或condition部分使用算术运算符(+、-、*、/),从而形成算术表达式。

具体规则:

1)、对数值型列、变量、常量可使用四则运算创建表达式;

2)、对日期型列、变量、常量可使用+、-运算符创建表达式。两个日期之间可进行减法运算,日期和数值之间可进行加、减运算;

3)、运算符不仅可在常量、变量之间进行运算,也可以在两列之间进行运算。

示例:

#数据列实际可当成一个变量

select teacher_id + 5 from teacher_table;#数据列部分使用算术运算

select * from teacher_table where teacher_id*2>4;#条件部分使用算术运算

select 3*5,20 from teacher_table;#显示常量


2、concat函数进行字符串连接

例:select concat(teacher_name,‘xxx’) from teacher_table; #选择出teacher_name与xxx连接的结果。对MySQL,如果与null连接,则连接结果为null。


3、取别名(别名仅在查询结果中)

1)、为数据列或表达式取别名时,别名紧跟数据列,中间以空格隔开,或者使用as关键字隔开。

如:select teacher_id+5 as teacherNum;#为表达式取别名为teacherNum。

#为两个表达式取别名分别为ID、NAME。

select teacher_id +5  ID ,concat(teacher_name,‘xxx’) NAME from teacher_table where teacher_id>4;

2)、为表取别名

格式同上,如:

select * from teacher_table teacher;#为teacher_table取别名为teacher。

注:多个表同时查询时,同样可取别名。


4、distinct去除查询结果中重复行

语法:select后紧跟distinct即可。

说明:仅是去除查询结果中的重复行,而非数据表中重复行。如表中有(1,'x'),(1,'y'),在数据表中不重复,但若只select第一列,则认为查询结果重复,查询结果将只保留一行。


5、查询结果排序:order by

语法:

select * from tableName order by columnName1 [asc|desc] [,columnName2 [asc|desc],……];

注:asc:升序,默认值;desc:降序。多行排序列,asc与desc单独指定。

例:

#学生姓名与性别组合排序,学生姓名降序排序,姓名相同时,按性别升序(默认)排序。

seletct * from tableName order by student_name desc,student_sex;


6、比较运算符与逻辑运算符

比较运算符:

1)、SQL中比较运算符:>、>=、<、<=、=、<>(不相等运算符)、:=(赋值运算符。)

2)、SQL特殊比较运算符:

-->between and,语法:expr1 between expr2 and expr3,即要求expr1>=expr2,且expr1<=expr3。注意expr2<=expr3!

-->in ,语法:expr1 in (expr2,expr3,……),要求expr1等于括号里面的任意一个值;

-->like,字符串匹配,like后的字符串支持通配符‘_’和‘%’。其中下划线可代表任意一个字符,百分号可代表任意多个字符。

语法:

select * from tableName where teacher_name like ‘李%’;#选出姓李的教师记录

select * from tableName where teacher_name like '李_';#选出姓李的且名字为两个字的教师记录

select * from tableName where teacher_name like '___';#选出名字为三个字的教师记录

select * from tableName where teacher_name like '\_%';  #MySQL中提供‘\’作为转义字符,选出下划线开头的名字的教师记录。

select * from tableName where teacher_name like ‘\_%’ escape '\'; #与上一条相等。SQL中无转义字符,需要escape关键字显示进行转义。

-->is null,语法:select * from tableName where teacher_name is null; #选出教师名为null的记录。

注意:因为SQL标准中null不等于null,null=null将返回null,故不能用=null判断。

逻辑运算符:or 、and、not。

优先级:所有比较运算符(1级)>not(2级)>and(3级)>or(4级)。所有运算符>非>与>或。


SELECT 语法:


0 0